0

I have an element a that stores the number of checked check boxes. It is updated in my partial. I have access to element in my controller, however, I need to make it global since it will be used by most of my controllers. I have used a $rootScope variable and have tried to set it to the value of the a everytime it is updated using $scope.watch, however, this is not working.

Partial:

<p>You have selected: {{ a =(categories | filter:{checked: true }).length }} JOSCOS</p>

    <ul class="a">
    <li ng-repeat="item in categories" >
      <input type="checkbox" class="chk" ng-model = "item.checked">{{item.info.ct}}
      </input>
      </li>
     </ul>
<a href = "#x1" ng-click = "al()">Start the test</a>

My angular controllers:

myApp.controller('OneController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/data/JOSCO.json').success(function(data) {
    $scope.categories = data;
  });
 $scope.a = 0
    $rootScope.cat = $scope.a;
    $scope.$watch('$scope.a',function () {
      $rootScope.cat = $scope.a;
   });
   $scope.al = function(){
      alert($scope.a); //outputs properly
   };
}]);

Second controller(I have a different partial for this):

myApp.controller('DetailsController', ['$scope','$rootScope' ,function($scope, $rootScope) {

  $scope.catno = $rootScope.cat;
  alert($scope.catno);  //outputs as '0'
}]);
2
  • Are you missing to inject the $rootScope at the OneController Commented Jan 31, 2016 at 5:24
  • Um, I'm not sure. Im new to Angular. How do I do that Commented Jan 31, 2016 at 5:25

1 Answer 1

3

$scope.$watch accepts a number of different ways to specify what variable you will be watching. You can either specify a function:

$scope.$watch(function(){return $scope.myvar}, someWatchHandler)

or send in the variable directly:

$scope.$watch($scope.myvar, someWatchHandler)

or pass the variable in as a string:

$scope.$watch('myvar', someWatchHandler)

You are using the last one of these. Note that you do not need to prefix it with $scope -- if you do, it will not find the variable. Just remove $scope from $scope.a and it should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.