1

我正在开发的一个小 AngularJS 应用程序有问题。我主要是一个 jQuery 开发人员。所以对我放轻松;)

我有一个通过 $http 调用获取我的类别的工厂:

app.factory('simpleFactory', function($http, $routeParams) {
var categories = [];
var factory = {};

factory.getCategories = function() {
    return $http({
        url: '/system/getlist/',
        data: { id : pageID },
        method: "POST",
    })
    .success(function(addData) {
        categories = addData;
    });
}

return factory; });

我的控制器创建了一个从我的工厂获取数据的范围:

app.controller('loadCategories', function ($scope, simpleFactory) {
$scope.categories = [];
init();

function init() {
    $scope.categories = simpleFactory.getCategories();
}

});

现在我有一个从我的视图(createCategory())触发的第二个范围,以在我的类别中插入一个新项目。现在我想将这个新项目推送到我现有的 $scope.categories 中。我试图这样做:

$scope.createCategory = function(cat,catName,catLvl,catType) {
    var catName = catName;
    var parentID = cat.id;

    $http({
        url: '/system/createcategory/',
        data: { catName : catName, parentID : parentID, pageID: pageID, catLvl: catLvl, catType: catType },
        method: "POST",
    })
    .success(function(addData) {
        $scope.categories.push(addData); 

    }); 
}

最后一个控制器也存在于 loadCategories 控制器中。

问题:

当我尝试 push() 我的 $scope.categories 中的某些内容时,我收到以下错误:

TypeError: Object # has no method 'push'

有谁知道我为什么会收到这个错误?我在做不正确的事情吗?

ajax 调用完成并触发成功回调,但 push() 出现问题。

我只是在学习Angularjs,所以请耐心等待:)

4

2 回答 2

3
$scope.categories = simpleFactory.getCategories()

return promise object, but not an array. And promise object have no method push(). change getCategories() method to return an array.

于 2013-10-07T17:06:10.457 回答
1

Ph0en1x is correct, you need to let the promise execute and then assign the scope variable like:

simpleFactory.getCategories().then(function(data) {
  $scope.categories = data;
});

And I would change the simpleFactory to return the categories to as well to allow assignment.

于 2013-10-07T17:06:46.020 回答