Angularjs注意父范围的变化 [英] Angularjs watch for change in parent scope
问题描述
我正在写一个指令,我需要观察更改的父作用域。不确定我是否这样做是首选方式,但它不能使用以下代码:
I'm writing a directive and I need to watch the parent scope for a change. Not sure if I'm doing this the preferred way, but its not working with the following code:
scope.$watch(scope.$parent.data.overlaytype,function() {
console.log("Change Detected...");
})
它记录了窗口加载,但即使更改了overlaytype也不会再次登录。
This it logged on window load, but never again, even when overlaytype is changed.
我怎么能观看 overlaytype
进行更改?
How can I watch overlaytype
for a change?
编辑:这是整个指令。我不完全确定为什么我会得到一个子范围
here is the entire Directive. Not entirely sure why I'm getting a child scope
/* Center overlays vertically directive */
aw.directive('center',function($window){
return {
restrict : "A",
link : function(scope,elem,attrs){
var resize = function() {
var winHeight = $window.innerHeight - 90,
overlayHeight = elem[0].offsetHeight,
diff = (winHeight - overlayHeight) / 2;
elem.css('top',diff+"px");
};
var watchForChange = function() {
return scope.$parent.data.overlaytype;
}
scope.$watch(watchForChange,function() {
$window.setTimeout(function() {
resize();
}, 1);
})
angular.element($window).bind('resize',function(e){
console.log(scope.$parent.data.overlaytype)
resize();
});
}
};
});
推荐答案
你应该拥有数据子范围的属性,范围使用父范围和子范围之间的原型继承。
You should have the data property on your child scope, scopes use prototypal inheritance between parent and child scopes.
此外, $ watch 方法所期望的第一个参数是要评估的表达式或函数,而不是变量的值。所以你应该发送它。
Also, the first argument the $watch method expects is an expression or a function to evaluate and not a value from a variable., So you should send that instead.
这篇关于Angularjs注意父范围的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!