Reputation: 816
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'
}]);
Upvotes: 0
Views: 2220
Reputation: 1816
$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.
Upvotes: 3