我有以下代码,也可以在http://jsfiddle.net/garukun/u69PT/上进行调试。
视图:
视图:
<div data-ng-app="testApp">
<div data-ng-controller="testCtrl">
<strong>{{pkey}}</strong>
<span data-test-directive data-parent-item="pkey"
data-parent-update="update(pkey)"></span>
</div>
</div>
JS:
var testApp = angular.module('testApp', []);
testApp.directive('testDirective', function ($timeout) {
return {
scope: {
key: '=parentItem',
parentUpdate: '&'
},
replace: true,
template: '<div><p>{{key}}</p>' +
'<button data-ng-click="lock()">Lock</button>' +
'</div>',
controller: function ($scope, $element, $attrs) {
$scope.lock = function () {
$scope.key = 'D+' + $scope.key;
console.log('DIR :', $scope.key);
// Expecting $scope.$parent.pkey to have also been
// updated before invoking the next line.
$scope.parentUpdate();
// $timeout($scope.parentUpdate); // would work.
};
}
};
});
testApp.controller('testCtrl', function ($scope) {
$scope.pkey = 'golden';
$scope.update = function (k) {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.pkey, k);
$scope.pkey = 'C+' + k;
console.log('CTRL:', $scope.pkey);
};
});
基本上,我正在使用隔离作用域设置指令,在其中双向绑定来自父级作用域(pkey)的属性(key),还将一个方法(parentUpdate)委托为在父级作用域的上下文中调用。
现在,在指令中的ng-click事件处理程序期间,我想调用parentUpdate方法并在其中执行某些操作。当我调用该方法时,我希望我的父级作用域的模型已经得到更新。但实际上没有,这就是困扰我的原因。
这可能是由于中间缺少了一些$digest周期,因为用$timeout包装parentUpdate调用会按预期工作。
有人可以解释一下缺少了什么吗?或如何正确地调用parentUpdate?
lock()
函数中的$scope.key = 'D+' + $scope.key;
似乎没有任何效果,对吧? - jandersen