Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

$rootScope.$watch not working with object in Angularjs

I have got two controllers. I define a $rootScope variable in parent controller and change it according to clicked dropdown.

I want the change to be reflected in the child controller.

Parent Controller

$rootScope.variable = {'attr1':true, 'attr2':false, 'attr3':false}//initializing
vm.clickedDropDown = function(index) {
    $rootScope.variable = {'attr1':false, 'attr2':false, 'attr3':false }
    switch (index) {
        case 1: 
            $rootScope.variable={'attr1':true, 'attr2':false, 'attr3':false}
            break;
        case 2: 
            $rootScope.variable={'attr1':false, 'attr2':true, 'attr3':false}
            break;
        case 3: 
            $rootScope.variable={'attr1':false, 'attr2':false, 'attr3':true}
            break;
    }
}

Child Controller

$rootScope.$watch($rootScope.variable,function(){
  console.log($rootScope.variable);
  console.log("changed");
},true)

The variable is changing and i am able to see the change in variable as output.

Upvotes: 0

Views: 6267

Answers (2)

emran
emran

Reputation: 922

You can simply use scope because the child controller will inherit the parent controller and have access to any scope variables defined in scope and rootScope

HTML:

<div ng-controller="MyCtrl">
  <input type="text" ng-model="name">
  <div ng-controller="ChildCtrl">
    <pre>{{ debug }}</pre>
  </div>
</div>

JS:

function MyCtrl($scope, $rootScope) {
    $rootScope.name = 'Superhero';
}

function ChildCtrl($scope, $rootScope) {

    $rootScope.debug = '';

    $scope.$watch('name', function(newVal, oldVal) {
        $scope.debug += " value changed...";
    });
}

jsfiddle: http://jsfiddle.net/heavyhorse/aqbhco7m/

Upvotes: 0

AlexD
AlexD

Reputation: 4310

Your watch is wrong.

Either:

$rootScope.$watch('variable' ,function(){
  console.log($rootScope.variable);
  console.log("changed");
},true);

or

$rootScope.$watch(
    function() { 
        return $rootScope.variable; 
    },
    function(){
        console.log($rootScope.variable);
        console.log("changed");
    },true);

Upvotes: 3

Related Questions