我有一个孤立范围的指令。我想检测作为父作用域变量的属性的更改。
到目前为止,我有以下内容:
var app = angular.module("app", []);
app.controller("ctrl", function($scope, $timeout) {
$timeout(function() {
console.log("called");
$scope.isReady = true;
$scope.$apply();
}, 2000);
});
app.directive("car", function($log) {
return {
scope: {
make: "=carMake"
},
restrict: 'E',
template: "<strong ng-bind='make'></strong>",
link: function(scope, elem, attrs) {
scope.$watch(attrs.shouldDo, function(value) {
var val = value || null;
if (val) {
$log.info(scope.$eval(attrs.shouldDo));
}
}, true);
}
}
});
http://fiddle.jshell.net/8Qhuk/
如果我将范围设置为false
它可以正常工作,但是我需要它来处理隔离范围。
答案 0 :(得分:4)
只需将scope
部分写为:
scope: {
make : "=carMake",
shouldDo: '='
},
修正演示 Fiddle
指令示例:
app.directive("car", function($log) {
return {
scope: {
make: "=carMake",
shouldDo: '='
},
restrict: 'E',
template: "<strong ng-bind='make'></strong>",
link: function(scope, elem, attrs) {
scope.$watch(function() {
return scope.shouldDo
},
function(newValue, oldValue) {
var val = newValue || null;
if (val) {
$log.info(scope.shouldDo);
}
});
}
}
});
在watch
我们只听一个变通。您不需要true
标志
顺便说一句,你可以使用 bind一次进行只读
scope: {
make : "=carMake",
shouldDo: '@'
},
HTML时的:
<car car-make="make" should-do="{{isReady}}"></car>
演示2 Fiddle