angularjsparentwatchcontrolleras

angular controller as watch variable in parent controller


how do i watch a variable, that is bind to a parent controller?

function config($stateProvider) {
    $stateProvider
        .state('home', {
            url: '/',
            templateUrl: 'home.html',
            controller: 'HomeController',
            controllerAs: 'vm'
        })

        .state('home.child', {
            url: '/child',
            templateUrl: 'child.html',
            controller: 'ChildController',
            controllerAs: 'vm'
        });
}

function HomeController($scope) {
    this.title = 'Some Title';
}

function ChildController($scope) {
    var vm = this;
    $scope.$watch('vm.title', function(current, original) {
        $log.info('title was %s', original);
        $log.info('title is now %s', current);
    });

}

The watch-Function doesn't recognize changes on the parent title..

thanks! :)


Solution

  • Just access the $parent scope when referencing objects belonging to the parent. Also get used to a cleaner and more standardized way of structuring your controller JS.

    HTML

    <html ng-app="myApp">
      <body>
        <div ng-controller="HomeController">
          <input type="text" ng-model="title">
          <div ng-controller="ChildController"></div>
        </div>
      </body>
    </html>
    

    JS

    var app = angular.module("myApp", []);
    app.controller("HomeController", ['$scope', '$log', function ($scope, $log) {
      $scope.title = "Some Title";
    }]);
    
    app.controller("ChildController", ['$scope', '$log', function ($scope, $log){
      $scope.$watch('$parent.title', function(newValue, oldValue) {
        $log.info('title was %s', oldValue);
        $log.info('title is now %s', newValue);
      });
    }]);