2015-01-06 59 views
0

我讀directiveng-attr,但我想給屬性的陣列指令爲例:屬性發送陣列指令

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

所以,How我可以在指令元素中設置數組屬性嗎?

回答

1

在你的指令鏈接功能

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

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