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

时间:2015-09-21 15:21:01

标签: javascript angularjs

我尝试将属性指令传递给元素指令,是否可能?我尝试过这样做但不起作用。

例如我有元素指令:

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

1 个答案:

答案 0 :(得分:1)

我做了类似于你尝试做的事情,但我不得不在编译中注入属性。您需要先将模板添加到$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);
               };
            }
        };
    }])
相关问题