简体   繁体   中英

Pass an attribute directive to an element directive

I try to pass an attribute directive to an element directive, is it possible? I tried do it as in example but it doesn't work.

for example I have element directive:

  <np-form-input 
        np-form-input-attrs="np-my-attr-directive"            
        >                
  </np-form-input>

JS:

.directive('npFormInput', [function () {
        return{
            restrict: 'E',
            templateUrl: '/resources/view/common/form_input',
            link: function(scope, element, attr){
                scope.attributes= attr.npFormInputAttrs;
            }
        };
    }])

And then in directive HTML

 <input
       {{attributes}}                                                             
       >

Thanks in advance.

EDIT: My solution based on Micah Williamson answer:

.run(['$templateCache', '$http', function($templateCache, $http){                          
    $http.get('/resources/view/common/form_input').success(function(data){
        $templateCache.put('/resources/view/common/form_input', data);                    
    });
}])
.directive('npFormInput', ['$templateCache', '$compile', function ($templateCache, $compile) {
        return{
            restrict: 'E',
            compile: function (ele, attrs) {
                var tpl = $templateCache.get('/resources/view/common/form_input');                            
                tpl = tpl.replace('{{attributes}}', attrs.npFormInputAttrs);

                var tplEle = angular.element(tpl);
                ele.replaceWith(tplEle);

                return function (scope, element, attr) {
                    $compile(tplEle)(scope);                            
                };
            },
        };
    }])

I've done something similar to what you're trying to do but I had to inject the attributes in the compile. You would need to add the template to $templateCache first though.

.directive('npFormInput', [function ($templateCache, $compile) {
        return{
            restrict: 'E',
            compile: function(ele, attrs) {
               var tpl = $templateCache.$get('/resources/view/common/form_input');
               tpl = tpl.replace('{{attributes}}', attrs.npFormInputAttrs);

               var tplEle = angular.element(tpl);
               ele.replaceWith(tplEle);

               return function(scope, element, attr){
                   $compile(tplEle)($scope);
               };
            }
        };
    }])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM