Reputation: 9
I have a directive, which watches for a inout box for old and new value. I would want to update the rootscope value here "total" . I tried to use all, that I knew like $rootScope, broadcast the message, emit the message. Here is the code.
app.directive('costCheck',function($compile,$rootScope,$timeout){
$rootScope.gName= "What did i buy?";
return{
restrict: 'A',
link: function(scope,element,attrs){
attrs.$observe('costCheck',function(value){
});
scope.$watch('cost',function(oldval,newval){alert(attrs.name);
alert(oldval+'--'+newval);
var message = {type: 'channel', action: 'create', data: { name: "ssss", id: 0}};
$rootScope.$broadcast('get',message);
});
}
}
});
This is my main controller
app.controller('MainCtrl', function($scope,$rootScope) {
$scope.totalCost = 'workinggg';
$rootScope.$on('go', function() {alert();
$scope.totalCost = 'working';
});
});
How to update the rootscope.
Upvotes: 0
Views: 1883
Reputation: 64883
I agree with the comment from @haki that you should bind the scope values from the controller/directive as shown.
scope : { value : '=value'}
But if you are wanting to broadcast for other reasons (i.e. other controllers) then change $rootScope.$on to $scope.$on. $scope is a child of $rootScope and the broadcast sends the message down to child scopes.
Here is a fiddle showing the binding to the directive scope working.
Edit: fiddle update to set totalCost on $rootScope in the directive
Edit 2: fiddle update to broadcast value down from $rootScope, and handled in another controller
Upvotes: 1
Reputation: 6066
There are many ways to accomplish this, and I wouldn't do it this way, but I'm just trying to make your code work here.
Directive code:
$rootScope.$emit('totalCostUpdated',message);
Main controller:
app.controller('MainCtrl', function($scope,$rootScope) {
$scope.totalCost = 'workinggg';
$rootScope.$on('totalCostUpdated', function(event, args) {
$scope.totalCost = 'working';
});
});
I would probably do it with a shared service, though. Take a look at https://egghead.io/lessons/angularjs-sharing-data-between-controllers .
Upvotes: 0