Angularjs将指令的所有属性传递给视图

时间:2015-08-09 21:18:32

标签: javascript angularjs angularjs-directive

我正在普通HTML <my-input>之上构建一个微小的角度指令<input>

因为这将在框架中可用,我需要允许人们将他们可能使用的任何属性从指令传递给input元素。例如:

<my-directive disabled="disabled" type="email">

会渲染

<input disabled="disabled" type="email">

我知道如果我有一个静态的属性列表,我可以手动执行..但问题是我无法预测将添加哪些属性..所以我正在寻找一个通过 all 从指令到输入元素的属性。

由于

1 个答案:

答案 0 :(得分:6)

如果您想将多个属性传递给视图,可以将其添加到链接功能中。

这是你的指示:

<强>指令

(function(){

  function myInput($compile) {
      return{
          restrict: 'E',
          templateUrl: 'template.html',
          link: function(scope, elm, attrs){

            //Convert camelCase to dash
            function toDash(str) {
               return str.replace(/\W+/g, '-')
                         .replace(/([a-z\d])([A-Z])/g, '$1-$2');
            }

            //Retrieve input into the template
            var input = angular.element(document.querySelector('#myInput'));

            //Loop on attrs
            for (var key in attrs) {
              if (key[0] !== '$'){
                //Remove all attribute to the top level element
                elm.removeAttr(toDash(key));

                //Add our attribute to the input
                input.attr(toDash(key), attrs[key]);

                //Compile and link it to the scope
                $compile(input)(scope);
              }
            }

          }
        };
  }

angular
  .module('app')
  .directive('myInput', myInput);


})();

使用模板:

<强> template.html

<input type="text" id="myInput">

例如,在控制器中,您可以设置一些变量:

控制器

(function(){

function Controller($scope) {

  $scope.show = true;

  $scope.toto = 'Hello !!'

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

并致电您的指令:

  <body ng-app="app" ng-controller="ctrl">

    <my-input disabled="disabled" ng-model="toto" ng-show="show"></my-input>

   </body>

因此,它会删除my-input元素的所有属性,并将其设置为模板。

相关问题