0

I read about ng-attr for directive, but I want to send array of attributes to directive as example:

<myElement attributes="attributes"></myElement>

And my directive as example:

myApp.directive('myElement', function(){
 return {
    restrict: 'E',
    require: 'ngModel',
    template: '<div>' + 
              '<!-- I want to add this attributes on the div element>' + 
              '</div>',
    replace: true,
    scope: {
        attributes: '=attributes'
    },            
  }
});

And the attributes is in controller as the following:

$scope.attributes = {"class": "test", "id": "test", "style": "color: 'red'"}

So, How can I set array of attributes in element in directive ?

Mohamed Yakout
  • 2,868
  • 1
  • 25
  • 45

2 Answers2

1

In link function of your directive

link:function(scope, element, attrs){
     var templateElement = angular.element(element[0].firstChild) //this is you template div el.
      angular.forEach(scope.attributes, function(value, key){
           //if you want to set the root element
           attrs.$set(key, value)
           //if you want to set template root div
          templateElement.attr(key, value)
      })
}
Mehmet Otkun
  • 1,374
  • 9
  • 22
0

html:

<my-element attributes="attributes"></my-element>

directive:

myApp.directive('myElement', function () {
            return {
                restrict: 'E',
                require: 'ngModel',
                template: '<div class="{{attributes.class}}" id="{{attributes.id}}" style="{{attributes.style}}">' +
                'I want to add this attributes on the div element' +
                '</div>',
                replace: true,
                scope: {
                    attributes: '=attributes'
                }
            }
        });

controller:

$scope.attributes = {"class": "test", "id": "test", "style": "color: red"};
BuriB
  • 1,343
  • 9
  • 16