将属性指令传递给元素指令

Pass an attribute directive to an element directive

本文关键字:指令 元素 属性      更新时间:2023-09-26

我尝试将属性指令传递给元素指令,这是可能的吗?我试着像例子中那样做,但它不起作用。

例如,我有元素指令:
  <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;
            }
        };
    }])

然后在指令HTML

 <input
       {{attributes}}                                                             
       >

提前感谢。

编辑:我的解决方案基于Micah Williamson的回答:

.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);                            
                };
            },
        };
    }])

我已经做了一些类似于你想做的事情,但我不得不在编译中注入属性。不过,您需要先将模板添加到$templateCache

.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);
               };
            }
        };
    }])