AngularJS:包装指令并传递属性

时间:2017-04-27 07:23:27

标签: javascript angularjs templates angularjs-directive

我正在寻找一种使用Angular 1.5扩展或包装第三方指令html的方法。

给出指令

<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>

然而,angular默认情况下将所有属性应用于根节点(此处:div)。

问题

如何将传递给my指令的所有参数/属性应用于模板的特定节点?

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

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

1 个答案:

答案 0 :(得分: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>'
  }
});