Angular Form Submit built with ng-repeat

Angular Form Submit built with ng-repeat

本文关键字:with ng-repeat built Submit Form Angular      更新时间:2023-09-26

我正在尝试使用Angular构建一个表单,该表单使用ng-repeat基于mongoDB中的字段创建输入。 我是角度的新手,所以我不太确定如何正确执行它。

以下是简化的 html:

<form ng-controller="SettingsFormCtrl as form" ng-submit="form.processForm()" novalidate>
    <div class="tabs">
        <div class="usertab" ng-repeat="(field,value) in formData.usertab">
             <input ng-model="{{field}}" name="{{field}}" value="{{value}}" required>
             <input type="submit">
        </div>
        <div class="infotab" ng-repeat="(field, value) in formData.infotab">
             <input ng-model="{{field}}" name="{{field}}" value="{{value}}" required>
             <input type="submit">
        </div>
    </div>
</form>

这是应用程序.js:

function SettingsFormCtrl($scope,$http){
var profile = this;
$http.get("api/profile/").success(function(response) {
    profile.result = response;
});
$scope.formData = profile.result;
$scope.processForm = function() {
    $http.post('pi/profile/submit', $scope.formData) .success(function(data) {
        console.log(data);
        if (!data.success) {
            // if not successful, bind errors to error variables
            alert('succes!');
        } else {
            // if successful, bind success message to message
            alert('no');
        }
    });
};
}
angular
.module('inspinia')
.controller('ProfileCtrl',ProfileCtrl)
.controller('SettingsFormCtrl',SettingsFormCtrl)

这是.get数据:

{
 "usertab":
           {
             "username":"Bob",
             "email":"bob@email.com"
           },
 "infotab":
           {
             "phone":"988-333-1245",
             "age":"44"
           }
}

任何帮助绝对不胜感激。

你的问题结构不好,但我注意到一些可能导致你的代码不起作用的错误

  1. 在您看来,在属性中绑定值时,不需要添加{{}}。Angular 将自动尝试将其解析为表达式。
  2. 在你的angular.module我不确定这是否是整个项目,但是要声明(创建)一个模块,你需要添加一个空数组[]或一个填充了你的依赖项的数组到模块,没有它,angular 会认为你正在尝试注入一个模块,当找不到它时, 它会抛出错误。
  3. 另一个关键的事情是,如果你做错$scope.formData,你把来自.get的响应存储在一个变量中,这超出了角度范围。当结果可用时,angular 将不知道,因此要完成这项工作,您需要将其直接存储到$scope.formData以便 angular 会在结果可用时立即更新视图。

为此创建了一个 plnkr,反映了我所做的更改

我希望这能回答你的问题。