[英]Dynamically Apply Attributes to DOM elements in ngRepeat in Directive
我正在用angular创建一个dropdown-menu
指令,并且有了一个主意。
无论如何,我可以在nr-repeat
attributes
的“列表” extend
到DOM元素吗?
<li ng-repeat="item in menuItems" ng-init="extend((current_element).attributes, item.attributes)" />
我唯一的问题是,我不知道如何获得上面的current_element
引用的内容。 最好只将current_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"
}
}
];
..我正在使用ng-repeat
。
现在,一旦我输入了我的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]);
}
}
我只想要一种更好的方法。 谢谢。
extend
DOM元素属性的可能且简单的方法是动态创建带有指令内项目的下拉列表。
.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));
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.