0

This is my outer directive's template file:

<div class="outerDirective">
    <span>{{imgLoadStatus}}</span> 

    <imgDirective class="innerDirective">
        <img src="img/src.jpg"/>
    </imgDirective>

</div>

As you can see I have two nested directives. One is holding the image and the outer one is displays the load status. I need to update the imgLoadStatus $scope variable of outer directive.

I know I can manage this with a kind of Pub/Sub service but I'm curios that is there a build in Angular way for this kind of job? Or do you prefer a diffrent way?

Lupus
  • 1,519
  • 3
  • 21
  • 38
  • just use `require`: http://stackoverflow.com/questions/15672709/how-to-require-a-controller-in-an-angularjs-directive – akonsu Jan 29 '14 at 03:07
  • @akonsu Ok that would work but I need more examples for fully understand this. – Lupus Jan 29 '14 at 03:15
  • 1
    http://stackoverflow.com/a/21292184/149060 - the nested scope in that example is very like the nested directives you have here. – Pauli Price Jan 29 '14 at 03:25

1 Answers1

1

Inside of your inner-directive's definition, you'd want to define a "scope" property.

angular.module(...).directive(..., ...function () {

    var innerDirective = {
        templateUrl : ...,

        scope : {
            loadingState : "="
        },

        link : function (scope, el, attrs, ctrl) {
            scope.update = function () {
                scope.loadingState.current += 1;
            };
        }
    };

    return innerDirective;

Inside of your outer-directive's template, when you call your inner-directive, you will add a "loading-state" attribute, and pass it a scope property from the outer-directive. // in your outer-directive: // $scope.loading.current = 0; // $scope.$watch("loading.current", function (newVal) { $scope.updateView(newVal); });

The loadingState : "=" is a two-way data-binding between the inner scope and the outer scope. The name you give it, inside of the inner-scope is the name of the property it expects in the HTML (almost like the HTML now has your constructor params).

There are cases where this will not go both ways, and will only go from parent to child.
Like if you try to make ngRepeat inner-directives.
Or if you use an ngIf to add/delete a child-directive.

I don't believe this is documented behaviour, but I do believe it's the current behaviour.

Norguard
  • 26,167
  • 5
  • 41
  • 49