1

I have a problem with a little AngularJS app I'm developing. I'm mostly a jQuery dev. so go easy on me ;)

I have a factory that is getting my categories through an $http call:

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; });

My controller creates a scope getting the data from my factory:

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

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

});

Now I have a 2nd scope which is triggered from my view (createCategory()) to insert a new item in my cateogories. Now I want to push this new item into my existing $scope.categories. I was trying to do it this way:

$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); 

    }); 
}

This last controller also lives in the loadCategories controller.

THE PROBLEM:

When I try to push() something inside my $scope.categories I get the following error:

TypeError: Object # has no method 'push'

Does anyone have an idea why I get this error? Am I doing stuff that is not correct?

The ajax call completes and the success callback is triggered, but something goes wrong with the push().

I'm just learning Angularjs, so please be patient :)

2 Answers 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Thank you very much. I was indeed working with the promise object, which is not an array ... therefore pushing data was not possible.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.