0

im sure im missing something probably very basic but cant seem to wrap my head around this issue. I am simple trying to push an object into a scope array on click. I am currently getting error: TypeError: Cannot read property 'push' of undefined(…)

Heres an example of what I got so far:

var app = angular.module('myApp', []);    

app.factory('MyService', function($http, $q, $timeout){

    var My_Stored_Data = {}

    return {

        template: function(){

            var template = { data1: "", data2: "", data3: "", data4: "" }
            return template

        }

    }              
});

Here is the controller:

app.controller('MyController', function ($scope,$q,MyService) {

    $scope.Main_scope = {};

    $scope.add_new_object = function(){

        $scope.Main_scope.My_array.push(MyService.template());
        //This give an error TypeError: Cannot read property 'push' of undefined(…) 
    }

});  

Anyone have anyidea what im missing?

2 Answers 2

2

You need to initialize My_array inside the Main_scope Object

app.controller('MyController', function ($scope,$q,MyService) {
     $scope.Main_scope = {};
     $scope.Main_scope.My_array =[];
Sign up to request clarification or add additional context in comments.

Comments

1

The error is verbose and clear My_array is not defined.

You need to define the array in your Main_scope variable.

$scope.Main_scope = {
    My_array : []
};

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.