Search code examples
javascriptarraysangularjsangularjs-ng-repeatonsen-ui

Dynamically add item to ng-repeat array javascript


I have to following array of items in angularjs

angular.module('app').controller('AppController', function ($scope, $timeout) {
    $scope.items = {
        item1: {
            name: "Hamburger",
            complete: "50%",
            start: "2015/09/10 11:00",
            finish: "2015/09/11 04:00",
            work: "8 hours"
        },
        item2: {
            name: "Pasta",
            complete: "50%",
            start: "2015/09/10 11:00",
            finish: "2015/09/11 04:00",
            work: "8 hours"
        },
        item3: {
            name: "Potato",
            complete: "80%",
            start: "2015/09/10 18:00",
            finish: "2015/09/11 04:00",
            work: "8 hours"
        }
    };

    $scope.items.push({
        item4: {
            name: "Ham",
            complete: "50%"...
        }
    });
}

I want to add a new item to it, but it's not working.

I tried .push(item) method, but it fails with the following message in the console

Object doesn't support property or method 'push'

What's the easiest way to add an item to this existing array?


Solution

  • Actually you are using object (not an array)

    Add value to object: $scope.items[key] = value;

    OR

    Initialize array instead of object $scope.items = [....];