Javascript 使用AngularJS中的JSON属性创建select
我想用您的attributeselect id创建一个select,select类来自在我的控制器中定义的JSON 有办法吗?或者我需要用select的代码做动态的分部吗 假设我不知道JSON中有哪些属性 谢谢 更新: 例如,如果我有这个JSON:Javascript 使用AngularJS中的JSON属性创建select,javascript,angularjs,Javascript,Angularjs,我想用您的attributeselect id创建一个select,select类来自在我的控制器中定义的JSON 有办法吗?或者我需要用select的代码做动态的分部吗 假设我不知道JSON中有哪些属性 谢谢 更新: 例如,如果我有这个JSON: { "topology" : [ { "name": "id", "value":"topology_id" }, { "name": "class", "value": "topology_class1 topo
{ "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标记中。使用更新的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];
}
};
});
下面是代码的一个实用技巧:不要介意样式,它是用来显示正在添加属性的。谢谢你的回答,但是试着假设你不知道JSON中的属性是什么。我想把所有的属性都放进去,不管JSON中包含什么属性。你有JSON的例子吗?如果JSON包含许多不同类型的属性,那么定制指令可能是最好的选择。非常感谢。