我想创建一个带有来自JSON的属性(select id,select class)的select(它在我的控制器中定义)。
有办法做到这一点吗?或者我是否需要使用select的代码执行动态部分?
假设我不知道JSON中有哪些属性。
谢谢!
更新
例如,如果我有这个JSON:
{ "topology" : [
{ "name": "id", "value":"topology_id" },
{ "name": "class", "value": "topology_class1 topology_class2" },
{ "name": "diasbled", "value": "disabled" }
]
}
我想获得这个选择标签:
<select id="topology_id" class="topology_class1 topology_class2" disabled="disabled"></select>
如果我有另一个带有其他属性的JSON,那么这些属性将出现在我的select标签中。
答案 0 :(得分:1)
使用更新的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/(不介意样式,它可以显示正在添加属性。)