【问题标题】:AngularJS: Wrapping Directives and passing the attributesAngularJS:包装指令并传递属性
【发布时间】:2017-04-27 07:23:27
【问题描述】:

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


给定一个指令

<lib-input></lib-input>

我想创建一个指令&lt;my-lib-input&gt; 来呈现以下 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)。

问题

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


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

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

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive


    【解决方案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>'
      }
    });
    

    【讨论】:

    • 谢谢,但这正是我想避免的,因为我需要指定每个可能传递给输入指令的范围参数。不仅因为它是一个“长”列表,还因为我的指令与我没有预料到的任何东西不兼容(例如可能在未来更新中添加的功能)。
    • 您可以要求父指令的控制器获取参数列表。如果你愿意,我可以更新答案。
    • 听起来不错,我真的很感激举个例子!
    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2016-05-03
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多