【问题标题】:AngularJS : $watch within directive is not working when $rootScope value is changedAngularJS:当 $rootScope 值更改时,指令内的 $watch 不起作用
【发布时间】:2015-01-31 15:50:52
【问题描述】:

我创建了一个应用程序是 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);
        }
    };
});

【问题讨论】:

    标签: angularjs angularjs-directive watch angularjs-watch


    【解决方案1】:
    scope: {},
    

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

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

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

    【讨论】:

      【解决方案2】:

      我已经更正了。对于工作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);  
          }
        };
      });
      

      【讨论】:

      • 你能告诉我这是我遇到的问题吗
      • 你不能直接在指令中使用 rootscope。通过使用范围使用 2 方式绑定:{ name : '=' }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多