Angularjs Pass all attributes as specified by view

I am building a tiny angular directive <my-input>

on top of regular HTML <input>

.

And since this will be available within the framework, I need to allow people to pass in some attribute that they can use from the directive for the input element. For example:

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

will display

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

I know that if I have a static list of attributes, I can do it manually. But the problem is that I cannot predict which attributes will be added .. so I am looking for a solution that traverses all attributes from the directive to the input element.

thank

+3


source to share


1 answer


If you want to pass multiple attributes to the view, you can execute it in the link function .

Here is your directive:

Directive

(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);


})();

      

With a template:

template.html

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

      



For example, in a controller, you can set some variable:

Controller

(function(){

function Controller($scope) {

  $scope.show = true;

  $scope.toto = 'Hello !!'

}

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

})();

      

And name your directive:

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

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

   </body>

      

This way it will remove all attributes on the element my-input

and set it to your template.

+4


source







All Articles