我知道這是一個老問題,但谷歌把我帶到這裏,我不喜歡這裏的答案......他們似乎的東西,應該是簡單非常複雜。所以我創造了這個指令:
*****新內容*****
因爲我已經使這個指令更通用,支持解析(典型的角度值)「屬性」屬性。
/**
* Author: Eric Ferreira <http://stackoverflow.com/users/2954747/eric-ferreira> ©2016
*
* This directive takes an attribute object or string and adds it to the element
* before compilation is done. It doesn't remove any attributes, so all
* pre-added attributes will remain.
*
* @param {Object<String, String>?} attributes - object of attributes and values
*/
.directive('attributes', function attributesDirective($compile, $parse) {
'use strict';
return {
priority: 999,
terminal: true,
restrict: 'A',
compile: function attributesCompile() {
return function attributesLink($scope, element, attributes) {
function parseAttr(key, value) {
function convertToDashes(match) {
return match[0] + '-' + match[1].toLowerCase();
}
attributes.$set(key.replace(/([a-z][A-Z])/g, convertToDashes), value !== undefined && value !== null ? value : '');
}
var passedAttributes = $parse(attributes.attributes)($scope);
if (passedAttributes !== null && passedAttributes !== undefined) {
if (typeof passedAttributes === 'object') {
for (var subkey in passedAttributes) {
parseAttr(subkey, passedAttributes[subkey]);
}
} else if (typeof passedAttributes === 'string') {
parseAttr(passedAttributes, null);
}
}
$compile(element, null, 999)($scope);
};
}
};
});
對於OP的使用情況下,你可以這樣做:
<li ng-repeat="color in colors">
<span attributes="{'class': color.name}"></span>
</li>
或者使用它作爲一個屬性指令:
<li ng-repeat="color in colors">
<span attributes="color.name"></span>
</li>
***** END新內容** ****
/**
* Author: Eric Ferreira <http://stackoverflow.com/users/2954747/eric-ferreira> ©2015
*
* This directive will simply take a string directive name and do a simple compilation.
* For anything more complex, more work is needed.
*/
angular.module('attributes', [])
.directive('directive', function($compile, $interpolate) {
return {
template: '',
link: function($scope, element, attributes) {
element.append($compile('<div ' + attributes.directive + '></div>')($scope));
}
};
})
;
對於q中的具體情況題目了,一個可以只改寫指令一下,以便它通過類的指令適用於跨度,像這樣:
angular.module('attributes', [])
.directive('directive', function($compile, $interpolate) {
return {
template: '',
link: function($scope, element, attributes) {
element.replaceWith($compile('<span class=\"' + attributes.directive + '\"></span>')($scope));
}
};
})
;
然後你可以使用這個在任何地方,並選擇通過動態名稱的指令。像這樣使用它:
<li ng-repeat="color in colors">
<span directive="{{color.name}}"></span>
</li>
我故意保持這個指令簡單明瞭。您可能(也可能會)必須對其進行修改以適應您的需求。
有趣的問題! – TheHippo 2013-04-28 18:33:37
我不確定這是可能的。您可以將color.name作爲參數傳遞給單個指令,然後檢查該值並從那裏運行/調用相應的代碼。 – mikel 2013-04-28 20:54:44