wesbos wesbos - 29 days ago 21
Javascript Question

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...");
})


This it logged on window load, but never again, even when overlaytype is changed.

How can I watch
overlaytype
for a change?

Edit: 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();
});
}
};
});

Answer

You should have the data property on your child scope, scopes use prototypal inheritance between parent and child scopes.

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.