Search code examples
angularjsangularjs-service

Angularjs - Declaring factory with a single object with a nested array - getting ReferenceError: .... is not defined


I have a factory with several different methods and I am trying to declare an object that has an array nested in it. That one nested array will be the main driving force for my app and it will have nested arrays as well(many more). However, I do want the nested array to stay nested in that one object. I tried the following but I keep getting error that myObject is is undefined.

app.factory('myService', function() {
    return {
        myobject: {name: "MockName", version: "1", myArray: []},
        addToArray: function(){
            this.myobject.myArray.push({name: "Something + " (typeof(myObject.myArray) === 'undefined' ? 1 : myObject.myArray.length, anotherArrayInside: []})
        },
        .......
    };
});

I am still a novice in Angular so I have no idea how to fix this problem. Any suggestions?

SOLVED

So I figured out that I didn't put one piece of code and that piece of code was causing my issue:

it was the myObject.myArray , because myObject.myArray was not defined yet, it was giving me an error. I have since changed that to typeof(myObject) === 'undefined'


Solution

  • This is a Javascript problem.

    app.factory('myService', function() {
        var myobject = {name: "MockName", version: "1", myArray: []}
        return {
            addToArray: function(){
                myobject.myArray.push({name: "Something" , anotherArrayInside: []})
            },
            .......
        };
    });