Dynamically Apply Attributes to DOM elements in ngRepeat in Directive

时间:2015-06-25 18:36:32

标签: javascript angularjs

I am creating a dropdown-menu directive in angular and had an idea.

Is there anyway that I can extend a "list" of attributes to a DOM element within an nr-repeat?

<li ng-repeat="item in menuItems" ng-init="extend((current_element).attributes, item.attributes)" />

My only problem is that I do not know how to get what I refferred to as the current_element above. It may even be better to just pass the current_element to a function:

<li ng-repeat="item in menuItems" ng-init="attributeExtend(current_element, item)" />

To be more descriptive, say I have an array:

var menuItems = [
    {
        label: "One"
        attributes: {
            style: "background-color: blue"
        }
    },
    {
        label: "Two"
        attributes: {
            style: "background-color: red"
        }
    },
    {
        label: "Three"
        attributes: {
            style: "background-color: green"
        }
    }
];

..which I am using for my ng-repeat.

Now, once I enter my function called by my ng-init:

<!--HTML-->
    <li class="upper-li" ng-repeat="item in menuItems" ng-init="extend(current_element, item, $index)" />

<!--SCRIPT-->
    scope.extend = function(elem, item, $index)
    {
        /*
            elem should be equal to:

                $element.find('li.upper-li')[0].children[$index]

            ..which I've discovered I can use as a work around,
            but I am still looking for my answer...
        */

        for(var key in item.attributes)
        {
            elem.setAttribute(key, item.attributes[key]);
        }
    }

I just want a better way of doing this. Thanks.

1 个答案:

答案 0 :(得分:1)

DOM元素的extend属性的可能且简单的方法是使用指令内的项动态创建下拉列表。

 .directive("dropdown", function() {
      return function(scope, element, attrs) {
        var data = scope[attrs["dropdown"]];
        if (angular.isArray(data)) {
          var listElem = angular.element("<select>");
          element.append(listElem);
          for (var i = 0; i < data.length; i++) {
            var option = angular.element('<option>'); 
            for(var key in data[i].attributes)
            {
                option.attr(key, data[i].attributes[key])
            }
            listElem.append(option.text(data[i].label));
          }
        }
      }
    });

Plunker http://plnkr.co/edit/pj8QedIpbyUZVYyopQ5R