我创建了一个应用程序是 angularjs,其中我有一个指令,我在指令中观察以在 $rootScope 变量发生变化时触发指令中的一些方法,但问题是当 $ rootScope.name 值已更改指令内的 watch 不起作用
我的代码如下
var module = angular.module('myapp', []);
module.controller("TreeCtrl", function($scope, $rootScope) {
$scope.treeFamily = {
name : "Parent"
};
$scope.changeValue = function()
{
$rootScope.name = $scope.userName;
};
});
module.directive("tree", function($compile) {
return {
restrict: "E",
transclude: true,
scope: {},
template:'<div>sample</div>',
link : function(scope, elm, $attrs) {
function update()
{
};
scope.$watch('name', function(newVal, oldVal) {
console.log('calling');
update();
}, true);
}
};
});
最佳答案
我已经更正了。工作 fiddle
<div ng-app="myapp">
<div ng-controller="TreeCtrl">
<input type="text" ng-model="userName"/>
<button ng-click="changeValue()">Change</button>
<tree name="name">
</tree>
</div>
</div>
module.directive("tree", function($compile) {
return {
restrict: "E",
transclude: true,
scope: {
name: '='
},
template:'<div>sample</div>',
link : function(scope, elm, $attrs) {
function update()
{
};
scope.$watch('name', function(newVal, oldVal) {
console.log('calling');
update();
}, true);
}
};
});
关于 Angular : $watch within directive is not working when $rootScope value is changed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27265695/