0

I have two directive, I want to count how much sons in father tag and display the counter in index.html as shown after JS files, the problem is that I didn't get the number correctly

   module.directive('directiveFather', function () {

    return {

    restrict: 'E',
    scope: {},
    controller: function ($scope) {

        $scope.AllCounter = 0;

        this.addCounter = function () {

            $scope.AllCounter = $scope.AllCounter + 1;

        }

    }


}

})

  module.directive('directiveSon', function () {

return {

    restrict: 'E',
    scope: {},
    require: '^directiveFather',
    link: function(scope, element, attrs, fatherCtrl){
      fatherCtrl.addCounter();
     }
    }


}

})

<directive father>

 <directive son>

 </directive son>
 {{AllCounter}}

 </directive father>

1 Answer 1

0

If you use an isolate scope, then the elements inside directiveFather will be bound to the parent scope (thus AllCounter won't be directly available in the view - although it will hold the correct value).


You can either change scope: {} to scope: true/false in directiveFather (see demo 1) or
"manually" compile, link and append the HTML to the directiveFather element (see demo 2).
(There is, also, Wildhoney's suggestion of using transclusion and template.)

Basically, you don't need any of that for the approach to work - they are only necessary to demonstrate that everything works (by displaying the counter in the view), but even without appending the counter, the addChild() function gets called as expected.


That said, after fixing the element names (<directive-father> and <directive-son>), it works as expected.


See, also, these short demos: demo 1, demo 2.

Sign up to request clarification or add additional context in comments.

3 Comments

Otherwise implement it using the factory/service approach.
The problem with the factory/service approach is that the implementation for supporting multiple directiveFather instances will be considerably more complex.
Don't you want something like the following: http://jsfiddle.net/abzf0mem/?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.