2017-04-27 73 views
0

我正在寻找一种方法来扩展或包装Angular 1.5的第三方指令html。AngularJS:包装指令并传递属性


给出一个指令

<lib-input></lib-input> 

我想创建一个指令<my-lib-input>这使得下面的HTML:

<div> 
    <my-directive></my-directive> 
    <lib-input ng-if="vodoo()"></lib-input> 
</div> 

这是应该以同样的方式被用作原始指示。


用我的指令,以同样的方式为原始的,我需要的所有属性移动到我的模板的一个特定节点:

<my-lib-input ng-model="model" ng-change="ctrl.onChange()"></my-lib-input> 

应该产生:

<div> 
    <my-directive></my-directive> 
    <lib-input ng-if="vodoo()" ng-model="model" ng-change="ctrl.onChange()"></lib-input> 
</div> 

然而,角应用所有的属性添加到根节点(这里是:div)。

问题

我如何申请所有的参数/属性被传递给我的指令模板的特定节点?


我想,以防止硬编码可用参数列表在我的指令,如:

restrict: 'E', 
scope : { 
    ngModel: '=', 
    ngChange: '&', 
    ...  
} 

回答

1

你可以有范围参数链接像 工作的jsfiddle here

var myApp = angular.module('myApp',[]); 
myApp.controller('myCtrl', function($scope) { 
    $scope.input = 'LibInput'; 
    $scope.changeInput2 = function(i2) { 
    $scope.myInputs.setInput2(i2); 
    } 

    //this is releaving module which have getters and setter and variables can be hidden from outside scope. 
    var getInputData = function() { 
    var input1 = 'Input1'; 
    var input2 = 'Input2'; 
    return { 
     getInput1 : function() { 
     return input1; 
     }, 
     getInput2 : function() { 
     return input2; 
     }, 
     setInput1 : function(i1) { 
     input1 = i1; 
     }, 
     setInput2 : function(i2) { 
     input2 = i2; 
     } 
    } 
    } 

    $scope.myInputs = getInputData(); 
}); 
myApp.directive('libInput', function() { 
    return { 
    restrict : 'E', 
    scope : { 
     input : '=' 
    }, 
    template : '<div>{{input}}</div>' 
    } 

}); 

myApp.directive('myLibInput', function() { 
    return { 
    restrict : 'E', 
    scope : { 
     input : '=', 
     myDirInput : '=' 
    }, 
    template : '<my-dir other-input="myDirInput"></my-dir>\ 
          <lib-input input="input"><lib-input>' 
    } 

}); 

myApp.directive('myDir', function() { 
    return { 
    restrict : 'E', 
    scope : { 
     otherInput : '=' 
    }, 
    template : '<div>{{otherInput.getInput1()}}</div>\ 
          <div>{{otherInput.getInput2()}}</div>' 
    } 
}); 
+0

谢谢,但这正是我想要避免的,因为我需要指定可能传递给输入指令的每个范围参数。不仅仅因为它是一个“长”列表,而且因为我的指令不会与任何我没有预料到的(例如可能在未来更新中添加的功能)兼容。 –

+0

您可以要求您的父指令的控制器获取参数列表。如果你愿意,我可以更新答案。 –

+0

听起来不错,我真的很感激一个例子! –