Search code examples
javascriptangularjsforeachrootscope

$rootScope not updating using forEach


Funny behaviour? My menus object contains menu items which in this moment of code are = true. this snippet is running in a factory.

angular.forEach($rootScope.menus, function(menu){
   menu = false;
   console.log(menu); // outputs false
})
console.log($rootScope.menus); //values are still equal to true

It would seem that while the value in the loop is being set to false, it is not being applied to the $rootScope, or rather not updating? Does the new value need to be applied?

Kind Regards,


Solution

  • The forEach has a copy of the array element passed in (passed by value instead of passed by reference). To update the original array use $rootScope.menus[i]:

    angular.forEach($rootScope.menus, function (menu, i) {
        $rootScope.menus[i] = false;
    });