简体   繁体   中英

Dynamically Apply Attributes to DOM elements in ngRepeat in Directive

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.

The possible and easy way to extend attributes of an DOM element is to dynamically create you dropdown list with items inside a directive.

 .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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM