[英]angularjs $watch is not working in directive
Trying to load data in directive by using one-way binding here is the code. 尝试通过使用单向绑定在指令中加载数据是代码。
<nav-directive depts="dummyData"></nav-directive>
APP.directive('navDirective', navDirective);
here is directive 这是指令
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 is undefined when data updated by conroller. 由控制器更新数据时,未定义scope.depts。
The syntax $scope.$watch('someString')
tells Angular to watch the value of the variable named someString
in the given $scope
. 语法
$scope.$watch('someString')
告诉Angular监视给定 $scope
名为someString
的变量的值。 Here you use it on the $rootScope
, so it will look for a variable depts
defined on the rootScope, and it won't find one because depts
is only defined on scope
. 在这里,您可以在
$rootScope
上使用它,因此它将查找在rootScope上定义的变量depts
,但找不到它,因为depts
仅在scope
定义。
So just use scope.$watch('depts')
. 因此,只需使用
scope.$watch('depts')
。
Try this, its working. 试试这个,它的工作。 Use 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="angular.js@1.4.x"></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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.