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
的变化?
这里是整个指令.不完全确定为什么我要获得儿童范围
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();
});
}
};
});
推荐答案
您应该在子作用域上拥有 data 属性,作用域在父作用域和子作用域之间使用原型继承.
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屋!