AngularJS在数组元素中设置动态键 [英] AngularJS set dynamic key in array element

查看:80
本文介绍了AngularJS在数组元素中设置动态键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的代码,



HTML

 < div ng-controller =myCtrl> 
< form ng-submit =sendPost()>
< input ng-model =newName [12]/>
< button type =submit>发送< / button>
< / form>
< / div>

控制器

  angular.module('myApp',[])
.controller('myCtrl',function($ scope,$ http){
$ scope.hello = {name:Boaz};
$ scope.newName = [];
$ scope.sendPost = function(){
console.log($ scope.newName);

))

预期输出

  [12] => 13(输入值)
[15] => 14(输入值)




Que 按设置动态输入数组键我可以得到空的键值。



您也可以查看小提琴



在这个小提琴中,您可以在控制台中获得空的对象。

谢谢!

  $ scope.newName = {}; 

而不是:

  $ scope.newName = []; 

通过这种方式,发送到服务器的内容是:

  {
12:输入值,
15:输入值
}

我希望这是您要找的内容。


I have trouble to set dynamic array key.

Here is my code,

HTML

<div ng-controller="myCtrl">
    <form ng-submit="sendPost()">
        <input ng-model="newName[12]"/>
        <button type="submit">Send</button>
    </form>
</div>

Controller

angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
    $scope.hello = {name: "Boaz"};
    $scope.newName = [];
    $scope.sendPost = function() {
            console.log($scope.newName);
    }                   
})

Expected Output

[12] => 13 (Input value)
[15] => 14 (Input value)

Que By setting dynamic input array key i can get empty key values.

Also you can check fiddle.

In this fiddle you can get empty object keys in console.

Thank you !

解决方案

If you only want the keys that have been set to exist in the data you send to your server, then use an object instead of an array. like so:

$scope.newName = {};

Instead of:

$scope.newName = [];

This way, what's sent to the server would be:

{
    12: "Input value",
    15: "Input value"
}

I hope this is what you're looking for.

这篇关于AngularJS在数组元素中设置动态键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆