AngularJS if / else in ng-repeat

时间:2016-09-01 15:13:40

标签: angularjs angularjs-scope

我有这个...

controller: "photogridCtrl",
templateUrl: 'js/ng-assets/templates/directives/photogrid-view.html',
scope: '=info'

在我的控制器里我有2个。

$scope.home = [
    {
        img: 'img/burlington.jpg', 
        label: 'Burlington', 
        action: '#/', 
        row:'col-md-12', 
        class:''
    }

另一个是......

$scope.featured = [
    {
        img: 'img/kitchener.jpg', 
        label: 'Kitchener', 
        action: '#/', 
        row:'col-md-12', 
        class:''
    }

在我看来......

<div class="photo-grids">
    <div class="row">
        <div class='{{item.row}} margin-bottom' ng-repeat='item in home'>
        <a href="{{item.action}}" class="photo-item {{item.class}}" style="background-image:url({{item.img}});">
        <span class="photo-caption"><h4>{{item.label}}
        <br><small>Ontario</small></h4></span>
        </a>
    </div>
</div>

在我的主索引中,我有2个页面,我想要显示photogrid-view.html

<photogrid-view></photogrid-view>

<photogrid-view info='featured'></photogrid-view>

现在你可以在我的ng-repeat中看到"item in home"我只想问我如何将home更改为根据<photogrid-view info='featured'></photogrid-view中的变量而改变的内容如果它是特色,它将输出$scope.featured的值,如果info = home,则它将输出$scope.home的值。所以它就像......

如果信息==&#39; home&#39;然后ng-repeat="item in home"如果信息==&#39;&#39;特色,那么ng-repeat="item in featured"抱歉很长的解释。但是谢谢! :)

2 个答案:

答案 0 :(得分:1)

$scope.returnArray = function(){
    if($scope.info){
        return $scope.featured;
    }
    return $scope.home;
}

在视图中:

<div class='{{item.row}} margin-bottom' ng-repeat='item in returnArray()'>

或:

<div ng-init="entities = returnArray()"></div>
<div class='{{item.row}} margin-bottom' ng-repeat='item in entities'>

或只是在视野中:

<div ng-show="info" class='{{item.row}} margin-bottom' ng-repeat='item in featured'>
<div ng-hide="info" class='{{item.row}} margin-bottom' ng-repeat='item in home'>

答案 1 :(得分:1)

<div ng-if="info === 'featured'" class='{{item.row}} margin-bottom' ng-repeat='item in featured'></div>
<div ng-if="info === 'home'" class='{{item.row}} margin-bottom' ng-repeat='item in home'></div>

这可以通过ng-if轻松实现。在我看来,这比ng-show更好,因为如果条件满足,它只会将它附加到DOM,而ng-show只是隐藏它。