0

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.

2
  • 1
    Try without the 'this'. Factories are not new'ed up like services. Instead, the return value from your factory function is what's injected into your controller-in your case it's just an object literal. Commented Jul 26, 2014 at 0:06
  • Your example is either a poor abstraction of what you are trying to do or you are missing that assignment of primitives (i.e. a string) is by copy in Javascript so there is no value in trying to refer to second.secondFirst as it is the same as assigning the duplicate literal "hello!!!" Commented Jul 26, 2014 at 4:56

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I did think about that but for the given situation, it's best if i keep it within the return or the whole json is removed from the return... which can be crazy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.