【发布时间】:2014-04-28 18:02:43
【问题描述】:
我有一个具有隔离范围的指令,其值通过两种方式绑定到父范围。我正在调用一个更改父范围中的值的方法,但更改未应用于我的指令中。(不会触发双向绑定)。这个问题非常相似:
AngularJS: Parent scope not updated in directive (with isolated scope) two way binding
但我没有更改指令中的值,而是仅在父范围内更改它。我阅读了解决方案,在第五点中说:
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);
};
});
【问题讨论】:
-
对此处讨论的相同问题的更好解释:stackoverflow.com/a/27533683/2724125
标签: angularjs