【发布时间】:2015-10-21 02:34:22
【问题描述】:
我正在使用 scope.$watch 来查找基于属性的指令的更改。这些更改由视图中输入元素上的 ng-model 绑定启动。视图上的指令 attribute 正在使用指令中的 scope.$watch 进行监视。然而,更改事件似乎从未在指令中触发。是什么导致我的代码中断?
下面代码中突出显示的部分,我登录到控制台(在指令代码中,带有星号),从不触发。通过输入上的 ng-model 对控制器范围的更改不会传播到指令。
如果我将属性值更改为静态字符串,而不是通过 ng-model 绑定它,它就可以工作。
此代码取自 AngularJS 文档here 中的一个工作示例。我无法“发现差异”,因为文档中的代码与我的非常相似。
angular.module('myApp.advancedDirectives', [
'myApp.advancedDirectives.advancedDirectives-directive'
])
.value('data', { name: 'John', surname: 'Smith' })
angular.module('myApp.advancedDirectives.advancedDirectives-directive', [])
.directive('advancedDirectives', ['$interval', 'dateFilter', 'data', function ($interval, dateFilter, data) {
console.log(data.length);
function link(scope, element, attrs) {
var format,
timeoutId;
scope.$watch(attrs.advancedDirectives, function (theFormat) {
format = theFormat;
**console.log(theFormat);
updateTime();**
});
element.on('$destroy', function () {
$interval.cancel(timeoutId);
});
// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function () {
updateTime(); // update DOM
}, 1000);
function updateTime() {
scope.directiveScope2 = dateFilter(new Date(), format);
}
}
var theScope = {
directiveScope1: '=info'
}
return {
templateUrl: 'components/advancedDirectives/advancedDirectivesTemplate.html',
scope: theScope,
link: link
}
}]);
<div ng-controller="viewAdvancedDirectivesCtrl">
<div>
<div><input ng-model="theViewFormat"/></div>
<div>Data from the directive scope: <span advanced-directives="theViewFormat" info='data'></span></div>
</div>
</div>
<span style='background:yellow'>Advanced Directive. Here is some data: {{directiveScope1.name}} {{directiveScope1.surname}}, alive at {{directiveScope2}}</span>
【问题讨论】:
标签: angularjs