【问题标题】:Loop nested objects AngularJS [duplicate]循环嵌套对象AngularJS [重复]
【发布时间】:2018-06-24 07:49:07
【问题描述】:
{ 名称:“产品一”, 能见度:1, 重量:'0.5', 价格:'19.99' 自定义属性:[ { 属性代码:'图像', 值:'.img' }, { 属性代码:'special_price', 值:'13.99' } ] }, { 名称:“产品一”, 能见度:1, 重量:'0.5', 价格:'19.99' 自定义属性:[ { 属性代码:'图像', 值:'.img' }, { 属性代码:'special_price', 值:'13.99' } ] }

如何访问 ng-repeat 或 javascript 上的“special_price”值?

【问题讨论】:

  • 你可以这样做:让 obj 的 list for ng 重复,然后让 obj1 的 obj.custom_attribute
  • 你想要那个attribute_code键的值吗?
  • 是的。检索值:13.99

标签: javascript angularjs json nested


【解决方案1】:

有几种方法可以解决这个问题。

准备控制器中的数据

function ExampleCtrl (products) {
  this.$onChanges = (changes) => {
    if (changes.products) {
    this.specialProductPrices = this.products.reduce((map, product) => {
      map[product.id] = product.custom_attributes
        // @TODO: Account for a case when there is no special price.
        .find(({attribute_code}) => attribute_code === 'special_price').value;
      return map;
    }, {})
    }
  }
}

angular.module('foo').component('example', {
  bindings: {
    products: '<'
  },
  controller: [
    ExampleCtrl
  ],
  template: `
    <div ng-repeat="product in $ctrl.products track by product.id">
      Name: <span ng-bind="product.name"></span>
      Price: <span ng-bind="product.price"></span>
      Special Price: <span ng-bind="$ctrl.specialProductPrices[product.id]"></span>
    </div>
  `
})

然后该组件可以简单地用作&lt;example products="products"&gt;&lt;/example&gt;。这主要是 angularjs 领域的惯用方法, 并且总体受到鼓励,因为使用了一次准备数据而不是在每个 $digest 周期中循环多次的组件 + reducer。

在模板的循环中访问它

如果您必须在模板中执行此操作,您可以执行以下操作:

<div ng-repeat="product in $ctrl.products track by product.id">
  Name: <span ng-bind="product.name"></span>
  Price: <span ng-bind="product.price"></span>
  Special Price:
  <span>
    <span ng-repeat="customAttribute in product.custom_attributes track by customAttribute.attribute_code"
      ng-show="customAttributeattribute_code === 'special_price'"
      ng-bind="customAttribute.value">
    </span>
  </span>
</div>

但是不鼓励使用这种方法,因为它会创建永远不会显示的 DOM 元素(ng-if 在这种情况下由于中继器而无法使用。)。另外,如果有很多客户属性, 这将变得非常效率低下。

其他选项

还可以创建接收product.custom_attributes 并显示属性(如果存在)的组件,或者创建一个过滤器来挑选出属性。 这些方法留给读者作为练习。

【讨论】:

  • 我得到了意外的令牌:运算符 (>)
  • 你在使用 ES6 并且支持箭头函数吗?如果不是,请将() =&gt; 的所有实例替换为标准函数声明
  • 一切都好,它 gulp-uglify 是导致它的原因。谢谢!
猜你喜欢
  • 2018-02-07
  • 2019-05-04
  • 2018-03-23
  • 1970-01-01
  • 2020-11-30
  • 2021-05-19
  • 2017-09-30
  • 2010-10-13
相关资源
最近更新 更多