0

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'

Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96

2 Answers2

3

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: []})
        },
        .......
    };
});
jackdbernier
  • 1,542
  • 1
  • 17
  • 32
2

You might want to read this Angular Service Definition: service or factory

This isn't a problem of AngularJS but something you're doing wrong in JavaScript.

var yourobj = {...}
return { addToArray : function() { /* now yourobj is visible */ }

in any case, I made a jsfiddle with your code. your "this" makes it visible but a nicer approach is the reveal pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Community
  • 1
  • 1
Eduard Gamonal
  • 8,023
  • 5
  • 41
  • 46
  • This worked as well but I also used the design pattern that you showed me. I wish I could choose both answers but I had to choose the first answer. Thanks! – Georgi Angelov Jul 09 '13 at 15:28