【问题标题】:angularJS what's a good way to put dictionary in inputangularJS将字典放入输入的好方法是什么
【发布时间】:2017-02-14 18:40:58
【问题描述】:

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

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

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

这是在构造函数中

this.hashMap : Iint = {};
this.hashMap["Next Title"] = "data";
this.hashMap["Next Value"] = "more data;

html 中,我希望每个values(数据,更多数据)出现在它自己的输入文本框中,用户可以在其中编辑和更改字典中的值。在用户保存和更新数据之前,我需要验证和其他事情,所以我不确定是否应该制作一个重复的数组。

【问题讨论】:

  • 字典是什么意思?你能举个例子吗?
  • 编辑了更多细节

标签: angularjs


【解决方案1】:

看看这个例子。在您编辑答案之前,我在 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 中实现它可能是类似的路线。

【讨论】:

    【解决方案2】:

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

    &lt;div ng-repeat="(key, value) in myObj"&gt; ... &lt;/div&gt;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多