2016-09-08 70 views
0

試圖通過使用單向綁定來加載指令中的數據是代碼。

<nav-directive depts="dummyData"></nav-directive> 

APP.directive('navDirective', navDirective); 

這裏是指令時,數據由電腦板更新

function navDirective($state, navigationService,$rootScope) { 

return { 
    restrict: "E", 
    scope: { depts: '=' }, 
    templateUrl: '/app/shared/common-directives/navigation/navigation.view.html', 
    link: function(scope, elem, attr) { 
      $rootScope.$watch('depts', function(newVal, oldVal) { 
      // or $watchCollection if students is an array 
      if (newVal) { 
       console.log('in Dir'); 
       console.log(scope.depts) 
      } 
     },true); 


    } 
}; 
} 

scope.depts是不確定的。

+2

爲什麼'$ rootScope。$ watch'?嘗試'範圍。$ watch'。我想'$ rootScope'中只有'depts'才能被觀察 – k102

回答

2

語法$scope.$watch('someString')告訴Angular觀察給定的$scope中名爲someString的變量的值。在這裏,您在$rootScope上使用它,因此它將查找在rootScope上定義的變量depts,並且它不會找到一個,因爲depts僅在scope上定義。

所以只是使用scope.$watch('depts')

+0

我試過了,它沒有工作,但現在它的工作是通過使用範圍。謝謝 – naCheex

2

試試這個,它的工作。使用scope.$watch

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.dummyData = 'World'; 
 
}); 
 

 
app.directive('navDirective', function() { 
 
return { 
 
    restrict: "E", 
 
    scope: { depts: '=' }, 
 
    template: '<div>test</div>', 
 
    link: function(scope, elem, attr) { 
 
      scope.$watch('depts', function(newVal, oldVal) { 
 
      // or $watchCollection if students is an array 
 
      if (newVal) { 
 
       console.log('in Dir'); 
 
       console.log(scope.depts) 
 
      } 
 
     },true); 
 

 

 
    } 
 
}; 
 
});
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link href="style.css" rel="stylesheet" /> 
 
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="[email protected]"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body ng-app="plunker" ng-controller="MainCtrl"> 
 
    <nav-directive depts="dummyData"></nav-directive> 
 
    depts value: <input ng-model="dummyData"/> 
 
    </body>