angularJS将字典放入输入的好方法

时间:2017-02-14 18:40:59

标签: angularjs

我在控制器中有一个数据字典,我正在使用ng-repeat显示它。 key是标题,value被放置为value的{​​{1}}字段。我希望用户能够编辑值,然后提交表单。什么是我能处理所有输入的最佳方式?我试过input但是我无法直接更改字典的值,所以我倾向于制作另一个字典来存储新数据。这似乎不是很有效,但我想知道是否有更好的方法。

编辑:我有这个界面并添加一些值。

ng-model

这是在构造函数

export interface Iint {
    [title: string] : string;
}

this.hashMap : Iint = {}; this.hashMap["Next Title"] = "data"; this.hashMap["Next Value"] = "more data; 我希望每个html(数据,更多数据)出现在它自己的输入文本框中,用户可以在其中编辑和更改字典中的值。在用户保存和更新数据之前,我需要验证和其他事情,因此我不确定是否应该制作重复的数组。

2 个答案:

答案 0 :(得分:0)

查看此示例。在编辑答案之前,我在Angular v1中实现了它。

https://plnkr.co/edit/9Y33BDQTngPZx2Vpx5Zz?p=preview

的script.js

var app = angular.module('myApp',[]);
app.controller('MyCtrl', ['$scope', function($scope) {

  $scope.dict = {
    "Title1" : "Hello World !",
    "Title2" : "Beautiful day",
    "Title3" : "How about that!?"
  };

  $scope.submitForm = function() {
    console.log($scope.dict);
    alert(JSON.stringify($scope.dict));
  };
}]);

的index.html:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="myApp">
    <h1>Dictionary Inputs</h1>
    <div ng-controller="MyCtrl">
      <form name="myForm" ng-submit="submitForm()">
        <ul>
          <li ng-repeat="(key,val) in dict">
        {{key}} : <input type="text" ng-model="$parent.dict[key]"> 
          </li>
        </ul>
        <button type="submit"> Submit</button>
      </form>
      <br/>
      <div>
         $scope.dict : {{dict}}
      </div>
    </div>
  </body>
</html>

在Angular v2中实现它可能在类似的行上。

答案 1 :(得分:0)

可以使用以下语法让ngRepeat迭代对象的属性:

<div ng-repeat="(key, value) in myObj"> ... </div>

参考:https://docs.angularjs.org/api/ng/directive/ngRepeat#iterating-over-object-properties

相关问题