Nate Cheng
Nate Cheng

Reputation: 464

$watch binded variable in parent and nested controller

I have a question about $watch and the scope in nested controller.

I have an input binded with a ng-model. For example, in my html

    <input ng-model='searchString' />  

This is within the child(nested) controller, but I defined ng-model in parent controller. So I tried to $watch in parent controller. It doesn't work.

    app.controller('mainCtrl', ['$scope', function($scope){
        $scope.searchString = '';
        $scope.$watch('searchString', function(){
            console.log("changed in parent");
        })
    }]);
    app.controller("nestedCtrl", ["$scope", function($scope){        
    }])

However, if I put $watch in child controller it would work.

    app.controller("nestedCtrl", ["$scope", function($scope){ 
        $scope.$watch('searchString', function(){
            console.log("changed in child");
        })
    }])

Why I defined the scope in parent controller but can only watch in child controller? Any ways could let parent controller detect the changes? Because I need to do something out of child controller but based on this scope variable, but I couldn't.

Upvotes: 0

Views: 145

Answers (2)

Hugo Meneses
Hugo Meneses

Reputation: 103

That is because AngularJS child scopes copy the elements that are primitives from the parents, and reference the ones that are inherited from Objects. So, the child scope has a copy of searchString defined in the beginning.

Here's an example: https://jsfiddle.net/NitroInside/p85he1du

The detailed explanation is here: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Upvotes: 0

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

The quickest and dirtiest will be the following:

You can add a method to parent $scope and then call it from child watcher through $scope.$parent.method().

But it's not a good approach. You should avoid that. Usually to resolve such problems you should create service and inject it in both child and parent controller and communicate through it.

Upvotes: 0

Related Questions