2013-11-22 54 views
0

使用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属性和作用域对象,这可以正常工作(显示表单)。我在这里错过了有关双向数据绑定的内容吗?还是有更好的方法来做到这一点? - 谢谢

回答

0

看起来很奇怪,你追加HTML而不编译。我想改变link首先:

.... 
link: function(scope, element, attrs) { 
     var attributes = angular.fromJson(attrs.attributes); 
     var tpl = template(attrs.name, attributes, attrs.results); 
     var tpl_compiled = angular.element($compile(tpl)(scope)); 
     element.html(tpl_compiled); 
    } 
... 

通过这种方式,我们告诉过角新追加的数据做一个消化周期。也许这是隔离范围myVar没有解雇的原因。

希望这将有助于,

0

在HTML myVar的需要一个像我-VAR进行格式化。你真的需要这个指令的隔离范围吗?看看这个笨蛋,并加入Maxim Shoustin的例子。

Plunker