Search code examples
javascriptangularjsdirectiveprelink

AngularJS value change not visible in directives


I want to delay compiling child directive until a promise in parent directive's prelink will be resolved and value (CONFIG) will be overwritten.

In Parent's preLink:

    somePromise.then(function(){ 
       CONFIG = 1;
       elem.append($compile(template)(scope));
    }

Template contains Child directive, so Child's prelink is executing after promise's resolve. Now I want to access CONFIG in Child's prelink and it has old value ({}).

Why is it happening? Fiddle: http://jsfiddle.net/RmDuw/642/


Solution

  • When you do CONFIG = 1 in you directive, you are actually changing the value of a local variable, that happens to be the one injected by the Angular value service.

    Since it is a local variable that you are changing, the contents injected at the child directive are unchanged.

    In order to send a value to the child directive through the value service, you must do something like CONFIG.value = 1.

    This works because despite being local variables (one for each directive), they are references to same service, thus changes at the pointed object are visible to both references.