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 ?

0

2 Answers 2

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)
      })
}
Sign up to request clarification or add additional context in comments.

Comments

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"};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.