【问题标题】:Targeting nested array in ng-repeat在 ng-repeat 中定位嵌套数组
【发布时间】:2013-11-21 12:53:59
【问题描述】:

有人可以告诉我我在这里做错了什么吗?

我正在检索一些数据并作为“productInfo”注入到控制器中。

我可以很好地加载数据,但是当我想在 ng-repeat 中定位特定值时,我没有得到想要的结果。我得到的最好的是 JSON 中的最后一组数据。

我正在从服务器获取 JSON,并且可以根据需要更改格式。我刚开始使用 Angular,如果有一个简单的答案,我们深表歉意。

HTML:

<div ng-controller="ProductStandardCtrl">
  <p>Item:</p>
    <article ng-repeat="item in items"> 
        <img ng-src="{{item.img}}" class="logo" alt="">
        <h4>{{item.title}}</h4>
    </article>
</div>

JSON:

{
"description":"Lorem Ipsum",
"headline":"Promotion headline",
"items":{
    "Standard":
        {"img":"http://placehold.it/303x152",
        "title":"Standard Product 1"
        },
    "Standard":
        {"img":"http://placehold.it/303x152",
        "title":"Standard Product 2"
        },
    "Standard":
        {"img":"http://placehold.it/303x152",
        "title":"Standard Product 3"
        }
    }
}

谢谢

【问题讨论】:

    标签: javascript json angularjs angularjs-ng-repeat


    【解决方案1】:

    您的 json 中的 items 属性不是数组,因此您无法对其进行迭代。

    所需的格式应该是这样的:

    {
        "description":"Lorem Ipsum",
        "headline":"Promotion headline",
        "items":[
            {
                "img":"http://placehold.it/303x152",
                "title":"Standard Product 1"
            },
            {
                "img":"http://placehold.it/303x152",
                "title":"Standard Product 2"
            },
            {
                "img":"http://placehold.it/303x152",
                "title":"Standard Product 3"
            }
        ]
    }
    

    【讨论】:

    • 我明白了,ng-repeat="item in items" 会循环遍历 items 数组吗?
    • @Paul 完全正确。你可以看到一个工作小提琴here
    • 非常感谢我所需要的——我会阅读更多关于数组结构的内容。这是来自第三方,所以我会要求修改。
    【解决方案2】:

    items 中有相同的键。键必须是唯一的:

    "items":{
        "Standard":{
            ..
        },
        "Standard":{
            ..
        },
        "Standard":{
            ..
        }
    }
    

    应该是这样的

    "items":{
        "Standard1":{
            ..
        },
        "Standard2":{
            ..
        },
        "Standard3":{
            ..
        }
    }
    

    【讨论】:

    • 您的观点是正确的,但它不会使ngRepeat 起作用,因为items 不是数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多