2017-04-27 94 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

聽起來不錯,我真的很感激一個例子! –