繁体   English   中英

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

[英]Pass an attribute directive to an 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;
            }
        };
    }])

然后在指令HTML中

 <input
       {{attributes}}                                                             
       >

提前致谢。

编辑:我的解决方案基于米卡·威廉姆森答案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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