AngularJS:当$ rootScope值改变时,指令内的$ watch无效

时间:2014-12-03 07:09:33

标签: angularjs angularjs-directive watch angularjs-watch

我创建了一个应用程序是angularjs,其中我有一个指令,我在指令中看到一个监视器,当$ rootScope变量发生变化时触发指令中的某些方法,但问题是当$ rootScope.name值已更改指令内的监视不起作用

我的代码如下所示

Working Demo

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);
        }
    };
});

2 个答案:

答案 0 :(得分:5)

我已经纠正过了。工作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);  
    }
  };
});

答案 1 :(得分:3)

scope: {},

您使用隔离范围。它不从父作用域继承,因此在此作用域中不存在name。由于您直接在$rootScope中定义它,因此您可以在指令中访问它:

module.directive("tree", function($compile, $rootScope) {
    ...
    link : function(scope, elm, $attrs) {
       function update()
       {
       };
       $rootScope.$watch('name', function(newVal, oldVal) {

使用根范围不是最好的主意。我不会将name放入根范围开始。最好将它放入控制器的范围并使用绑定,类似于@simon提出的解决方案。

相关问题