简体   繁体   English

通过 ng-model 将键值对传递给函数

[英]Pass key-value pairs to function via ng-model

I have a function that gets an object from json, and I list its key-value pairs in ng-repeat.我有一个从 json 获取对象的函数,我在 ng-repeat 中列出了它的键值对。 It is a form where value is true/false and depending on that, it is checked or not.它是一种形式,其中值是真/假,并根据它进行检查或不检查。

<form class="form-horizontal">
  <div class="form-group form-group__bordered"
       ng-repeat="(key, value) in listOfNotificationTypes">

    <label for="inputEmail3">{{ key | trimkey }}</label>

    <div class="checkbox-wrapper">
        <input type="checkbox" class="checkbox" ng-checked="{{value}}">
    </div>
 </div>

 <div class="form-group">
    <div class="col-12 clearfix">
        <a href="#" class="btn"
            ng-click="updateNotificationSettings()">
         SAVE
        </a>
    </div>
 </div>
</form>

It all works well, but what I want is also to pick up those changed key-value pairs and send them via another function when I hit that SAVE button.一切都运行良好,但我还想要获取那些更改的键值对,并在我点击 SAVE 按钮时通过另一个函数发送它们。

How can I bind the input in ng-model so I have the correct json format passed, like如何在 ng-model 中绑定输入,以便传递正确的 json 格式,例如

{
   "key1":"value1",
   "key2":"value2",
   "key3":"value3",
    ...
  }

I suppose I should use ng-model to capture the data, but do not know how exactly to handle it.我想我应该使用 ng-model 来捕获数据,但不知道如何准确地处理它。

So, for your type of of object you will have to use the input like this.因此,对于您的对象类型,您将不得不使用这样的输入。

<input type="checkbox" class="checkbox" ng-model="listOfNotificationTypes[key]">

Here is a plunker demonstrating the implementation.这是一个演示实现的plunker

Notes: Just one few note in the future you may need to transform that object in a list of objects like this备注: 以后只需注意几个事项,您可能需要在像这样的对象列表中转换该对象

[
   {key: "key1", value: false},
   {key: "key2", value: true},
   {key: "key3", value: false}
  ];

For that case the code on the front end will be对于这种情况,前端的代码将是

<div class="form-group form-group__bordered" ng-repeat="notification in listOfNotificationTypes">
 <label for="inputEmail3">{{ notification.key }}</label>
  <div class="checkbox-wrapper">
    <input type="checkbox" class="checkbox" ng-model="notification.value">
  </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM