shrw
shrw

Reputation: 1801

angularjs nested directive with changing attribute

The directive simply hangs the entire site .. because of the nested directive call .. resolve this issue,, i a, abl

Here is my use case ..

Directive definition is given by:

app.directive('bluet', function($rootScope,$compile) {
    return {
        scope: {}, 
        restrict: 'E',
        replace: true,
        controller: function($scope, $element, $attrs, $parse, $timeout,$transclude) {
            $scope.val1;
        },      
        templateUrl:"partials/bluetTemplate.html",

        link: function(scope, element, attrs) {
            attrs.$observe('val1', function(value) { 
                if(value && value != undefined) {
                    scope.val1 =  value;
                }
            });
        }

}

and the calling html looks like ...

 <bluet val1="{{ val1 +'1' }}"></bluet>

the ng-template for partials/bluetTemplate.html would look something like :

<div>
  <span ng-if="val1=='111'">
    <bluet val1="{{ val1 +'1' }}" ><bluet>           
    <!-- nested call -->
  </span>
  <span>
    {{val1}}
  </span>    
</div>

Upvotes: 0

Views: 228

Answers (1)

gkalpak
gkalpak

Reputation: 48211

Since the ngIf directive will check the "end condition" during the post-link phase, while the template will be compiled during the compile phase, ther will be an ininite compile loop.

A possible approach would be to check the "end condition" (i.e. the value of val1) in post-link phase and (if necessary) create, compile and insert a new <bluet> child element dynamicaly.

E.g.:

app.directive('bluet', function($compile) {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        template: '<div><span>{{val1}}</span></div>',
        link: function postLink(scope, elem, attrs) {
            scope.val1 = attrs.val1;
            if ((scope.val1 !== undefined) && (scope.val1 !== '111')) {
                var bluet = angular.element(
                    '<bluet val1="' + scope.val1 + '1"></bluet>');
                $compile(bluet)(scope);
                elem[0].insertBefore(bluet[0], elem[0].firstChild);
            }
        }
    };
});

See, also, this short demo.

Upvotes: 3

Related Questions