Search code examples
javascriptangularjsangularjs-scopeangularjs-controllerangularjs-rootscope

AngularJS - $rootScope variable initialization fails


I'm trying to initialize a $rootScope array variable (arrayX) and use it in a $rootScope function in the same controller (controllerA).

The reason i'm using $rootScope instead of $scope for this variable and this function is that i'm planning to call them from another controller later.

The problem is that when I call the controller's $rootScope function i get a 'Uncaught TypeError: data.push is not a function etc.'

I believe that even if i declared the $rootScope arrayX = [] variable, this initialization is ignored or not recognized when I call the function. Can anyone explain me why I got this error and what i'm missing about the $rootScope concept? Thanks

THE CODE

angular.module('myApp')
  .controller('mainCtrl', function ($scope, $rootScope, $uibModal) {

//does this count as a valid variable initialization? 
$rootScope.localCart = [];

$rootScope.pushToCart = function (obj) {

    $rootScope.localCart.push(obj); //TYPEERROR
    ....

If i re-declare $rootScope.localCart in $rootScope.pushToCart function, things will be fine

    $rootScope.pushToCart = function (obj) {
        $rootScope.localCart = [];
        $rootScope.localCart.push(obj); // OK!
        ...

There's something i'm missing. Why is the outside-function initialization ignored? I thought that declare $rootScope variables in advance could be a nice idea (in order to avoid in-function declaration and confusion with other $scope variables...)

EDIT: Thanks everyone for the service suggestion. I'll try it as soon as possible (I need to sleep!) It's just that... I really wanted to understand why the $rootScope variable init. fails/is not recognized when I call the push method from the function.


Solution

  • If you are going to use $rootScope I would suggest to do the definition of the array and the function declaration into the run block, and then use it in the controller. So you can be sure that when you use the function, both are declared.

    But, you should be doing this in a services as many pointed out.