Angular : $watch within directive is not working when $rootScope value is changed

标签 angularjs angularjs-directive watch angularjs-watch

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

我的代码如下

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

最佳答案

我已经更正了。工作 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/

相关文章:

javascript - Angular 观察组未能始终如一地接收模型变化

angularjs - 在 AngularJS 中使用 ng-pattern 验证电子邮件

javascript - 从 addEventListener 函数向 ng-repeat 添加数据不会更新 DOM

angularjs - 何时在 Angular 中使用 transclude 'true' 和 transclude 'element'?

javascript - 编辑和保存不起作用

javascript - 配置vscode任务在parcel watch后复制文件

c++ - Visual Studio 2010 Professional 中的监视值不正确

javascript - 将表单数据从 Angular 传递到 php 文件

angularjs - Angular 1 - 路由和 API

javascript - 从指令 angularjs 引用 HTML 元素