AngularJS:指令中$手表不工作时,$ rootScope值被改变 [英] AngularJS : $watch within directive is not working when $rootScope value is changed
本文介绍了AngularJS:指令中$手表不工作时,$ rootScope值被改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一个应用程序中,我有一个指令,我ahving指令内的手表触发指令中的一些方法时,有在$ rootScope变量的变化angularjs,但问题是当$ rootScope.name值被改变手表这是指令中不能正常工作
我的code为如下
给出 VAR模块= angular.module('MyApp的',[]);module.controller(TREECTRL功能($范围,$ rootScope){
$ scope.treeFamily = {
名称:父
}; $ scope.changeValue =功能()
{
$ rootScope.name = $ scope.userName;
};});module.directive(树,函数($编译){
返回{
限制:E,
transclude:真实,
范围: {},
模板:'< DIV>样品LT; / DIV>,
链接:功能(范围,榆树,$ ATTRS){
功能更新()
{
};
范围。手表$('名',函数(的newval,OLDVAL){
的console.log('呼叫');
更新();
},真正的);
}
};
});
解决方案
我已经改正了。对于工作小提琴
< DIV NG-应用程序=的myapp>
< DIV NG控制器=TREECTRL>
<输入类型=文本NG模型=username的/>
<按钮NG点击=changeValue()>变化与LT; /按钮>
<树名称=名字>
< /树>
< / DIV>
< / DIV>module.directive(树,函数($编译){
返回{
限制:E,
transclude:真实,
范围: {
名称:'='
},
模板:'< DIV>样品LT; / DIV>,
链接:功能(范围,榆树,$ ATTRS){
功能更新()
{
};
范围。手表$('名',函数(的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
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值被改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文