【问题标题】:send array of attributes to directive将属性数组发送到指令
【发布时间】:2015-01-06 13:07:52
【问题描述】:

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

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

【问题讨论】:

    标签: arrays angularjs angularjs-directive


    【解决方案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)
          })
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-03-31
        • 2020-01-12
        • 2023-03-24
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2013-04-23
        • 1970-01-01
        相关资源
        最近更新 更多