[英]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.