Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'cheaper' performance-wise $broadcast or $watch

Tags:

angularjs

I have a situation in my application where I need to reload the menu each time the role of the user changes(One user can have roles in several companies).

I was wondering what is the best way to approach this issue.

currently I am doing the following:

app.controller('menuLoadingCtrl', function($location, $scope, authService){
    $scope.model.initialRole = authService.getRole();
    $scope.$watch(function(){return authService.getRole()}, function(val){
        if(val && val != $scope.model.initialRole){
                $scope.layout.menuSrc = 'partials/menu.html';
        }
    });
})

Simple redirecting the user to the menu loading view, and from there, back to the menu view once the role is done loading. I have this wrapped in a function:

 $scope.layout.reloadMenu = function(){
        $scope.layout.menuSrc = 'partials/menuLoading.html';
    }

which I call at any scenario at which I would like to reload the menu.

I was wondering if I can make this process more automatic by broadcasting this event from the service on the $rootScope, and then listening to it in the controller.

Any thoughts\advice on this will be greatly appreciated.

like image 745
Oleg Belousov Avatar asked Oct 27 '13 09:10

Oleg Belousov


1 Answers

$watch() is doing dirt-checking: the function makes a comparison each digest cycle. On the other hand, $broadcast() propagates an event only when there is one. Naturally, $broadcast() is cheaper than $watch().

But did you really have to worry about performance here? One primitive comparison by cycle is nothing. However, conceptually, $watch() is clearly what you need: you want to do an action each time a variable changes. I can't imagine using $broadcast() here.

like image 193
Blackhole Avatar answered Oct 20 '22 02:10

Blackhole