将属性数组发送到指令

send array of attributes to directive

我读到关于 ng-attrdirective,但我想将属性数组发送到指令,例如:

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

以我的指令为例:

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'
    },            
  }
});

控制器中的属性如下:

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

那么,如何在指令中的元素中设置属性数组?

在指令的link函数中

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)
      })
}

html:

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

指令:

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'
                }
            }
        });

控制器:

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