Add directives from directive in AngularJS

后端 未结 7 1754
庸人自扰
庸人自扰 2020-11-22 10:02

I\'m trying to build a directive that takes care of adding more directives to the element it is declared on. For example, I want to build a directive that t

7条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 10:05

    I wanted to add my solution since the accepted one didn't quite work for me.

    I needed to add a directive but also keep mine on the element.

    In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.

    angular.module('some.directive', [])
    .directive('someDirective', ['$compile',function($compile){
        return {
            priority: 1001,
            controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
    
                // controller code here
    
            }],
            compile: function(element, attributes){
                var compile = false;
    
                //check to see if the target directive was already added
                if(!element.attr('ng-style')){
                    //add the target directive
                    element.attr('ng-style', "{'width':'200px'}");
                    compile = true;
                }
                return {
                    pre: function preLink(scope, iElement, iAttrs, controller) {  },
                    post: function postLink(scope, iElement, iAttrs, controller) {
                        if(compile){
                            $compile(iElement)(scope);
                        }
                    }
                };
            }
        };
    }]);
    

提交回复
热议问题