我有一个带有隔离作用域的指令,其值与父作用域具有双向绑定。我调用了一个方法来更改父作用域中的值,但是该更改未应用于我的指令(双向绑定未被触发)。这个问题非常相似:AngularJS: Parent scope not updated in directive (with isolated scope) two way binding,但我没有在指令中更改值,而是仅在父作用域中更改它。我阅读了解决方案,在第五点中说到:
这意味着当我的父值更改为2时,将触发一个监视器。它会检查父值和指令值是否相同 - 如果不同,则复制到指令值。但是我的指令值仍然是1...我还缺少什么吗?
HTML:
The watch() created by the isolated scope checks whether it's value for the bi-directional binding is in sync with the parent's value. If it isn't the parent's value is copied to the isolated scope.
这意味着当我的父值更改为2时,将触发一个监视器。它会检查父值和指令值是否相同 - 如果不同,则复制到指令值。但是我的指令值仍然是1...我还缺少什么吗?
HTML:
<div data-ng-app="testApp">
<div data-ng-controller="testCtrl">
<strong>{{myValue}}</strong>
<span data-test-directive data-parent-item="myValue"
data-parent-update="update()"></span>
</div>
</div>
JS:
var testApp = angular.module('testApp', []);
testApp.directive('testDirective', function ($timeout) {
return {
scope: {
key: '=parentItem',
parentUpdate: '&'
},
replace: true,
template:
'<button data-ng-click="lock()">Lock</button>' +
'</div>',
controller: function ($scope, $element, $attrs) {
$scope.lock = function () {
console.log('directive :', $scope.key);
$scope.parentUpdate();
//$timeout($scope.parentUpdate); // would work.
// expecting the value to be 2, but it is 1
console.log('directive :', $scope.key);
};
}
};
});
testApp.controller('testCtrl', function ($scope) {
$scope.myValue = '1';
$scope.update = function () {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.myValue);
$scope.myValue = "2";
console.log('CTRL:', $scope.myValue);
};
});