2014-12-03 35 views
2

我創建了一個應用程序,其中我有一個指令,我正在監視指令內的某個表,以在指令內觸發某些方法在$ 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); 
     } 
    }; 
}); 

回答

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

你能告訴我笏是我正在做的問題 – 2014-12-03 08:06:54

+0

你不能直接使用rootcope裏面的指令。使用範圍使用2種方式進行綁定:{name:'='} – simon 2014-12-03 08:11:52

3
scope: {}, 

您可以使用一個孤立的範圍。它不從父範圍繼承,因此name在此範圍內不存在。既然你直接在$rootScope定義它,你可以訪問它在你的指令:

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

使用root範圍是不是最好的主意,雖然。我不會將name放入根範圍內。最好將其放入控制器的範圍並使用綁定,類似於@simon提出的解決方案。

相關問題