Javascript angularjs$watch在指令中不工作
尝试使用单向绑定在指令中加载数据的代码如下Javascript angularjs$watch在指令中不工作,javascript,angularjs,Javascript,Angularjs,尝试使用单向绑定在指令中加载数据的代码如下 <nav-directive depts="dummyData"></nav-directive> APP.directive('navDirective', navDirective); conroller更新数据时,scope.depts未定义。语法$scope.$watch('someString')告诉Angular在给定的$scope中查看名为someString的变量的值。在这里,您在$rootScope上使
<nav-directive depts="dummyData"></nav-directive>
APP.directive('navDirective', navDirective);
conroller更新数据时,scope.depts未定义。语法
$scope.$watch('someString')
告诉Angular在给定的$scope
中查看名为someString
的变量的值。在这里,您在$rootScope
上使用它,因此它将查找在rootScope上定义的变量depts
,但找不到,因为depts
仅在scope
上定义
因此只需使用
scope.$watch('depts')
语法$scope.$watch('someString')
告诉Angular在给定的$scope
中观察名为someString
的变量的值。在这里,您在$rootScope
上使用它,因此它将查找在rootScope上定义的变量depts
,但找不到,因为depts
仅在scope
上定义
所以只要使用
scope.$watch('depts')
试试这个,它可以工作。使用
var-app=angular.module('plunker',[]);
应用程序控制器('MainCtrl',函数($scope){
$scope.dummyData='World';
});
app.directive('navDirective',function(){
返回{
限制:“E”,
作用域:{depts:'='},
模板:“测试”,
链接:功能(范围、要素、属性){
范围.$watch('depts',函数(newVal,oldVal){
//或$watchCollection(如果学生是数组)
if(newVal){
console.log('in Dir');
console.log(scope.depts)
}
},对);
}
};
});代码>
安古拉斯普朗克
文件。写(“”);
部门价值:
试试这个,它很管用。使用
var-app=angular.module('plunker',[]);
应用程序控制器('MainCtrl',函数($scope){
$scope.dummyData='World';
});
app.directive('navDirective',function(){
返回{
限制:“E”,
作用域:{depts:'='},
模板:“测试”,
链接:功能(范围、要素、属性){
范围.$watch('depts',函数(newVal,oldVal){
//或$watchCollection(如果学生是数组)
if(newVal){
console.log('in Dir');
console.log(scope.depts)
}
},对);
}
};
});代码>
安古拉斯普朗克
文件。写(“”);
部门价值:
为什么$rootScope.$watch
?尝试范围。$watch
。我想在$rootScope
中没有部门需要监视为什么$rootScope.$watch
?尝试范围。$watch
。我想,$rootScope
中没有要监视的depts
。我尝试过它不工作,但现在它通过使用scope工作。ThanksI尝试过它不工作,但现在它通过使用范围工作。谢谢
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);
}
};
}