使用angularjs,我试图动态填充表单,然后通过POST提交表单数据到服务器。Angularjs数据绑定表单数据POST
我在控制器中创建一个数据变量(开机自检后)
$scope.data = {};
然后在我的HTML,形式
<div ng-repeat="(name, attributes) in fields">
<element myVar="data.{{name}}" name="{{name}}" attributes="{{attributes}}" ></element>
</div>
凡领域看起来像
创建的元素{"agency":{"name_displayed":"Agency","size":"30","tag":"input","type":"text"},"department":{"name_displayed":"Department","size":"30","tag":"input","type":"text"},"description":{"cols":"50","name_displayed":"Description","rows":"4","tag":"textarea"}}
元素指令然后看起来像这样,但抛出错误
demoApp.directive("element", function() {
var template = function(name, attributes, results) {
var templateString = "<" + attributes.tag;
for (var attribute in attributes) {
if (attribute != "name_displayed" && attribute != "tag" && attribute != "options") {
templateString += " " + attribute + '="' + attributes[attribute] + '"';
}
}
if (attributes.tag == "input") {templateString += ' value="' + results + '"';}
templateString += ' name="' + name + '">';
templateString += ' ng-model="myVar">';
if (attributes.tag == "select") {
for (var i=0; i<attributes.options.length; i++) {
templateString += "<option value=" + attributes.options[i] + ((attributes.options[i] == results)? " selected" : "") + ">" + attributes.options[i] + "</option>";
}
}
if (attributes.tag == "textarea") {
templateString += results;
}
templateString += "</" + attributes.tag + ">";
var toReturn = attributes.name_displayed + ": " + templateString;
return toReturn;
};
return {
restrict: "E",
scope: {
myVar: '='
},
link: function(scope, element, attrs) {
var attributes = angular.fromJson(attrs.attributes);
var tpl = template(attrs.name, attributes, attrs.results);
element.html(tpl);
}
};
});
没有指令中的myVar属性和作用域对象,这可以正常工作(显示表单)。我在这里错过了有关双向数据绑定的内容吗?还是有更好的方法来做到这一点? - 谢谢