0

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.

4

2 回答 2

1

您有两个不同的命名变量,一个是 localCart,另一个是 localCartUser。

在您的第一个片段中,您声明了 localCart,但随后您尝试推入未声明的 localCartUser 变量。

不要在 rootScope 上添加可重用功能,而是使用服务(请参阅我的评论)

于 2015-11-24T22:32:14.303 回答
1

如果您要使用 $rootScope,我建议您将数组的定义和函数声明放入 run 块中,然后在控制器中使用它。所以你可以确定当你使用这个函数时,两者都被声明了。

但是,正如许多人指出的那样,您应该在服务中执行此操作。

于 2015-11-24T23:08:43.543 回答