离子应用程序错误:array.push()不是函数

时间:2017-04-17 21:26:52

标签: javascript angularjs arrays ionic-framework

我创建了一个应用程序,我有控制器和工厂。我在工厂里面有一个数组,我希望将元素的id推送到这个数组。但是,当我试图将元素推送到数组时,我得到了一个错误

  

“favorites.push不是函数”

您可以在下面找到我的控制器和工厂。感谢您阅读: 的厂:

.factory('favoriteFactory',['$resource', 'baseURL','$localStorage', function ($resource, baseURL, $localStorage) {
            var favFac = {};
            var favorites = $localStorage.get('favorites', []);
          favFac.addFavorites = function (index) {
            for(var i=0; i<favorites.length; i++){
              if(favorites[i].id == index)
                return
            }
              favorites.push({id: index});
              $localStorage.storeObject('favorites',favorites)
          }
          favFac.deleteFromFavorites = function (index) {
            for (var i = 0; i < favorites.length; i++) {
              if (favorites[i].id == index) {
                favorites.splice(i, 1);
              }
            }
            $localStorage.storeObject('favorites', favorites)
          };

          favFac.getFavorites = function () {
            return $localStorage.getObject('favorites',[]);
          };
          return favFac
        }])

控制器:

    .controller('MenuController', ['$scope', 'menuFactory', 'favoriteFactory','baseURL', '$ionicListDelegate', 'dishes', '$localStorage',
         function($scope, menuFactory,favoriteFactory, baseURL, $ionicListDelegate, dishes, $localStorage) {


        $scope.baseURL = baseURL;
        $scope.tab = 1;
        $scope.filtText = '';
        $scope.showDetails = false;
        $scope.showMenu = true;
        $scope.message = "Loading ...";
        $scope.addFavorite = function (index) {
          console.log("index:" +index);
          favoriteFactory.addFavorites(index);
          $ionicListDelegate.closeOptionButtons();

        };
        $scope.dishes = dishes;

            $scope.select = function(setTab) {
              $scope.tab = setTab;

              if (setTab === 2) {
                $scope.filtText = "appetizer";
              }
              else if (setTab === 3) {
                $scope.filtText = "mains";
              }
              else if (setTab === 4) {
                $scope.filtText = "dessert";
              }
              else {
                $scope.filtText = "";
              }
                };
   $scope.isSelected = function (checkTab) {
      return ($scope.tab === checkTab);
    };

    $scope.toggleDetails = function() {
      $scope.showDetails = !$scope.showDetails;
    };
  }])

1 个答案:

答案 0 :(得分:0)

我假设你正在使用[]。 get方法没有第二个参数。因此,您尝试返回默认值undefined(空数组)只是返回undefined,然后您尝试推送到ngStorage而不是数组。

get的源代码没有显示var favorites = $localStorage.get('favorites', []); 的第二个参数: https://github.com/gsklee/ngStorage/blob/master/ngStorage.js

所以这一行:

var favorites = $localStorage.get('favorites') || [];

应该是这样的:

web.config