Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13842

Calling other functions within return of Angularjs Factory

I have a factory:

.factory('PageType', function () {
   return{
     first: {
       firstFirst: {
         firstFirstFirst: this.second.secondFirst
       },
       firstSecond: "yoyo!"

     },
     second: {
        secondFirst: "hello!!!"
     }
   }
})

the this.second.secondFirst will not work, but this.secondFirst will work. How can I call the second.secondFirst? I tried PageType.second.secondFirst but that errored out.

Upvotes: 0

Views: 54

Answers (1)

Nat
Nat

Reputation: 3077

So you want to reference the same value at two points in the object nesting? Why not assign it first to a variable before declaring the return object?

e.g.

myModule.factory('PageType', function () {
  secondFirst = "hello!!!";
  return {
    first: {
      firstFirst: {
        firstFirstFirst: secondFirst
      },
      firstSecond: "yoyo!"
    },
    second: {
      secondFirst: secondFirst
    }
  };
});

this.second.secondFirst and the like won't work because in that scope this refers to the anonymous function, (unless you wrap it in another anonymous function which is called as a method on the immediate parent object, however this object has no knowledge of the grandparent object that references it as a value). PageType.second.secondFirst also won't work because there is no PageType in scope inside the factory definition (only inside the subsequent function scope where PageType is injected).

EDIT:

A variation on this solution would be to declare the object structure without the double references then add them in as a separate statement before returning the object.

PageType = {
  foo: {
  }
};
PageType.foo.bar = PageType.baz = "hello";
return PageType;

Upvotes: 1

Related Questions