将属性数组发送到指令

时间:2015-01-06 13:07:52

标签: arrays angularjs angularjs-directive

我为directive阅读了ng-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'"}

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

2 个答案:

答案 0 :(得分: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)
      })
}

答案 1 :(得分: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"};