如何建立,而不是与角数组对象 [英] How to build object instead of array with angular

查看:137
本文介绍了如何建立,而不是与角数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器使用功能,增加了次关联数组:

I have a controller which adds times to an associative array using a function:

crtl.items = [];
ctrl.build_array = function (code, item) {
  crtl.items[code] = item;
}

我的问题是关联数组在JavaScript中是有问题所以这个作品:

My problem is associative arrays are problematic in javascript so this works:

<div>
  <p>{{ctrl.items['a']}}</p>
<div>

但是,这并不:

<div ng-repeat="item in ctrl.items">
  <p>{{item}}</p>
</div>

我怎样才能改变我的角度功能,因此它增加了项目到对象,而不是一个关联数组?

How can I change my angular function so that it adds items to a objects rather than an associative array?

推荐答案

对象和关联数组在JavaScript中同样的事情。而且你最好不要向它提供上键入一个假的暗示迷惑发动机;这...

Objects and associative arrays are the same things in JavaScript. And you'd better not confuse an engine by providing it with a false hint on type; this...

crtl.items = {}; // plain object, not an array!
ctrl.build_array = function (code, item) {
  crtl.items[code] = item;
}

...就够了,因为你其实可以遍历与 NG-重复太对象:

<div ng-repeat="(key, item) in ctrl.items">
  <p>{{item}}</p>
</div>

引用<一个href=\"https://$c$c.angularjs.org/1.4.6/docs/api/ng/directive/ngRepeat#iterating-over-object-properties\"相对=nofollow> 的文档

您需要注意的是,JavaScript规范没有定义
  键的顺序返回的对象。 (要在角缓解这种
  1.3使用的按键按字母顺序排序的 ngRepeat 指令。)

You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)

1.4版去掉字母排序。现在,我们靠的顺序
  运行为MyObj中键时,由浏览器返回。看起来
  浏览器一般按顺序提供密钥的策略
  它们被确定,尽管<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues\"相对=nofollow>也有例外的时候钥匙
  被删除,恢复。

Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser when running for key in myObj. It seems that browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated.

如果这不是想要的,建议的解决方法是转换你的
  对象成排进你preFER顺序的数组
  之前将其提供给ngRepeat。你可以用这种过滤器这样做
  为 toArrayFilter 或实施 $观看的对象自己。

If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.

这篇关于如何建立,而不是与角数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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