问题
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'
回答1:
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: []})
},
.......
};
});
回答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/
来源:https://stackoverflow.com/questions/17550895/angularjs-declaring-factory-with-a-single-object-with-a-nested-array-getting