user3498603
user3498603

Reputation: 9

Update root scope from an AngularJS directive

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

Answers (2)

Brocco
Brocco

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

Pieter Herroelen
Pieter Herroelen

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.

  • I guess you don't want to update the root scope (as the title says), but you want to communicate through the root scope.
  • As @Shomz said, you need to match the event names of course.
  • If you use $rootScope, you can just emit the event instead of doing a broadcast, then it doesn't have to bubble down in your app

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

Related Questions