简体   繁体   English

AngularJS-动态ng重复表达式

[英]Angularjs - Dynamic ng-repeat Expression

I want to make a dynamic page, that depending of some aspects shows one list or another list, both arrays have different variable names. 我想制作一个动态页面,根据某些方面显示一个列表或另一个列表,两个数组都具有不同的变量名。 I tried to use somethings to put dynamic ng-repeat expression but without success. 我试图用一些东西来放置动态ng-repeat表达式,但是没有成功。

Anyone has some suggestion? 有人有什么建议吗? I made a fiddle to explain what i need. 我做了一个小提琴来解释我的需要。

<div ng-repeat="item in itemsToShow" >
    <!--THIS IS THE EXPRESSION THAT I WANT DYNAMIC-->
 {{item.name}}, {{item.title}}

[fiddle] http://jsfiddle.net/eTTZj/867/ [小提琴] http://jsfiddle.net/eTTZj/867/

You could use operators : 您可以使用运算符:

    <div ng-repeat="item in itemsToShow" >
     {{item.name || item.firstname}},  {{item.title || item.titleBig}}
   </div>

This will pick the existing property in your list. 这将选择列表中的现有属性。

If it's unsunstainable for many, many lists you can also do this: 如果对于许多列表来说,这是不合理的,那么您也可以执行以下操作:

<div ng-repeat="item in itemsToShow"></div>
    <div ng-repeat="(key, value) in item">
        {{key}} : {{value}}
    </div>
</div>

I've updated your JSFiddle . 我已经更新了您的JSFiddle When you want to be 'dynamic', just code the logic inside the controller and set the $scope.itemsToShow with different arrays, so your view hasn't to change. 当您想变得“动态”时,只需在控制器内部编写逻辑并为$scope.itemsToShow设置不同的数组,这样您的视图就不会改变。

Like this: 像这样:

....
var show_items_2 = true;
/*Whatever you want to do here*/
if(show_items_2) {
   $scope.itemsToShow = items2;
} else {
    $scope.itemsToShow = items;
}

When you want to have different keys inside your array ('name' and 'nameBig'), you have to access the items differently (through (key, value)). 如果要在数组中使用不同的keys (“ name”和“ nameBig”),则必须以不同的方式(通过(键,值))访问各项。 See this SO question here . 在这里看到这个问题

<div ng-repeat="item in itemsToShow"></div>
<div ng-repeat="(key, value) in item">
    {{key}} : {{value}}
</div>

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

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