【问题标题】:How to store form data using angularjs?如何使用 angularjs 存储表单数据?
【发布时间】:2013-06-13 09:40:08
【问题描述】:

我创建了一个带有输入字段的表单,它显示了 json 文件的当前值。现在我想当用户更改值并提交表单时,我应该能够检索新值,然后将其写入 json 文件。 我现在的代码如下

html文件

<html ng-app>
<head>
  <script src="angular.min.js"></script>
  <script src="angularjs.js"></script>
</head>
<body ng-controller="teamsController">
  <form >
    <table>
        <thead>
            <th>TeamName</th><th>Wins</th>
        </thead>
    <tr ng-repeat="team in teams"><td><input type="text" value="{{team.teamName}}"></td>
    <td><input type="text" value="{{team.w}}"></td></tr>
    </table>
    <input type="submit" value="Save new values" ng-click="savedata()">
  </form>
</body>
</html>

js文件

var teamsController = function ($scope,$http) {
$http.get("teams.json").success(function(data)
{
$scope.teams=data.teams;
console.log(data);
console.log($scope.teams);
});
}

json文件是

{"leagueName":"American League", "abbr":"AL", "teams":[
    {"teamName":"Tampa Bay", "w":96, "l":66},
    {"teamName":"NY Yankees", "w":95, "l":67},
    {"teamName":"Boston", "w":89, "l":73},
    {"teamName":"Toronto", "w":85, "l":77},
    {"teamName":"Baltimore", "w":66, "l":96},
    {"teamName":"Minnesota", "w":94, "l":68},
    {"teamName":"Chicago White Sox", "w":88, "l":74},
    {"teamName":"Detroit", "w":81, "l":81},
    {"teamName":"Cleveland", "w":69, "l":93},
    {"teamName":"Kansas City", "w":67, "l":95},
    {"teamName":"Texas", "w":90, "l":72},
    {"teamName":"Oakland", "w":91, "l":81},
    {"teamName":"LA Angels", "w":80, "l":82},
    {"teamName":"Seattle", "w":61, "l":101}]}

非常感谢!

【问题讨论】:

    标签: json angularjs


    【解决方案1】:

    使用...ng-model="team.teamName"...ng-model="team.w" 代替...value="{{team.teamName}}"...value="{{team.w}}"

    另外,我强烈建议您学习 AngularJS phonecat 教程,该教程可以在 here 找到。它将详细解释如何制作一个最简单的 AngularJS 应用程序,并将大部分概念解释清楚。

    【讨论】:

    • 但问题是我想在表单字段中显示当前值,然后如果用户仍想进行更改并提交表单,则应将其保存或暂时存储在变量中
    • 你试过上面的方法了吗?它将显示输入中的当前值,当用户更改值时,$scope.teams 将自动更新为新值——这就是 AngularJS 的美妙之处。我认为您当然应该尝试 AngularJS 教程(我提供的链接)以了解您可以使用 AngularJS 做什么以及它是如何工作的。
    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2013-05-20
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多