MJohnyJ
MJohnyJ

Reputation: 129

AngularJS: $watch not called when changed in child scope

I have the following situation: In my parent scope, I define an object called rule, with an attribute called "keyword". On this keyword, I am setting a watcher:

$scope.$watch("rule.keyword", function(newKeyword){...});

Now, rule.keyword is found by a child scope and is changed by a child scope. This can happen e.g. with a ui-select, or a simple text box.

Still, the watcher is not calling its function, but in the parent scope, the variable has the correct value, set in the child scope.

Anyone has an idea, why the watcher is not firing?

Thank you!

Upvotes: 0

Views: 367

Answers (1)

Hussain Mahfoodh
Hussain Mahfoodh

Reputation: 308

You can trigger the watcher in the parent scope only as following:

$scope.$parent.$watch('property', function(value){...});

However, if you want the watcher to be triggered in both scopes, then you have to make the $scope variable to refer to the same object by updating its value in both parent and child scopes.

function ParentCtrl($scope) {
  $scope.rule = {ruleValue: val};
}

function ChildCtrl($scope) {
  $scope.update = function(ruleValue) {
    $scope.rule.keyword = ruleValue;
  };
}

Upvotes: 1

Related Questions