AngularJS:当 $rootScope 值更改时,指令中的 $watch 不起作用 [英] AngularJS : $watch within directive is not working when $rootScope value is changed

查看:27
本文介绍了AngularJS:当 $rootScope 值更改时,指令中的 $watch 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的代码如下

工作演示

var module = angular.module('myapp', []);module.controller("TreeCtrl", function($scope, $rootScope) {$scope.treeFamily = {姓名:家长"};$scope.changeValue = function(){$rootScope.name = $scope.userName;};});module.directive("tree", function($compile) {返回 {限制:E",转置:真实,范围: {},模板:'<div>sample</div>',链接:功能(范围,榆树,$ attrs){函数更新(){};scope.$watch('name', function(newVal, oldVal) {console.log('呼叫');更新();}, 真的);}};});

解决方案

我已经更正了.用于工作 fiddle

<div ng-controller="TreeCtrl"><input type="text" ng-model="userName"/><button ng-click="changeValue()">更改</button><树名=名称">

module.directive("tree", function($compile) {返回 {限制:E",转置:真实,范围: {名称:'='},模板:'<div>sample</div>',链接:功能(范围,榆树,$ attrs){函数更新(){};scope.$watch('name', function(newVal, oldVal) {console.log('呼叫');更新();}, 真的);}};});

I have created an application is angularjs in which i am having a directive, i am ahving a watch within the directive to trigger some methods within the directive when there is a change in $rootScope variable, but the problem is when the $rootScope.name value is changed the watch which is within the directive is not working

My code is as given below

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

解决方案

i have corrected it. for working 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);  
    }
  };
});

这篇关于AngularJS:当 $rootScope 值更改时,指令中的 $watch 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆