使用更新后的 JSON 文件,您可以执行以下操作:
// Your template
<select dynamic-attributes='topology'></select>
// The dynamic attributes directive
angular.module('yourModule')
.directive('dynamicAttributes', ['jsonData', function (jsonData) {
return function (scope, element, attrs) {
// Get the attribute data from a service.
var attributes = jsonData.get(attrs.dynamicAttributes);
// Add each of the attributes to the element.
attributes.forEach(function (attribute) {
element.attr(attribute.name, attribute.value);
});
}
}]);
// The jsonData service
angular.module('yourModule')
.service('jsonData', function () {
// This would really come from the server.
var json = {
"topology" : [
{ "name": "id", "value":"topology_id" },
{ "name": "class", "value": "topology_class1 topology_class2" },
{ "name": "diasbled", "value": "disabled" }
]
};
// Public API
return {
get: function (name) {
return json[name];
}
};
});
这是代码的工作小提琴:http: //jsfiddle.net/nfreitas/SmWE8/(不要介意样式,它在那里表明正在添加属性。)