将属性动态应用于指令中ngRepeat中的DOM元素

Dynamically Apply Attributes to DOM elements in ngRepeat in Directive

本文关键字:ngRepeat 中的 DOM 元素 指令 属性 动态 应用于      更新时间:2023-09-26

我正在创建angular中的dropdown-menu指令,并且有一个想法。

我是否可以将extendattributes的"列表"nr-repeat中的DOM元素?

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

我唯一的问题是我不知道如何获得上面所说的current_elementcurrent_element传递给一个函数可能会更好:

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

为了更具描述性,假设我有一个数组:

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

我正在将其用于我的CCD_ 7。

现在,一旦我进入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]);
        }
    }

我只是想要一个更好的方法。谢谢

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

Plunkerhttp://plnkr.co/edit/pj8QedIpbyUZVYyopQ5R