从数组中选择一个项目而不是重复

时间:2015-01-30 11:50:44

标签: angularjs ionic-framework

当我使用ng-repeat时,我遍历数组并将其全部吐出,但是我想使用与soemthign相同的数据源,只选择其中一个。

而不是使用ng-repeat和过滤到我认为必须有更好方法的一条记录。

 .controller('ViewBarsCtrl', function ($scope) {
        $scope.bars = [
            { title: 'Toms Bar', id: 1, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
            { title: 'Haydens Bar', id: 2, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
            { title: 'Jackis Jaunt', id: 3, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
            { title: 'Alans Place ', id: 4, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
            { title: 'Harveys Local', id: 5, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
            { title: 'Mitchells Spot', id: 6, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" }
        ];
    })

那是我的控制者。我通过状态参数获得了BarID,所以我想选择适合BarID的行,并且能够像我的html中那样{{$scope.bar.title}}

1 个答案:

答案 0 :(得分:0)

您可以循环显示条形,匹配ID,并将该条指定给新变量:

var id = idYouGotFromState;
for (var i = 0; i < $scope.bars.length; i++) {
    if ($scope.bars[i].id === id) {
        $scope.bar = $scope.bars[i];
        break;
    }
}

然后您就可以使用{{bar.title}}了。


在此处查看:

&#13;
&#13;
angular.module('app', [])
  .controller('ViewBarsCtrl', function($scope) {
    $scope.bars = [
        { title: 'Toms Bar', id: 1, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
        { title: 'Haydens Bar', id: 2, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
        { title: 'Jackis Jaunt', id: 3, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
        { title: 'Alans Place ', id: 4, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
        { title: 'Harveys Local', id: 5, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" },
        { title: 'Mitchells Spot', id: 6, strapline: "Potential Strapline?", picture: "img/test/pub.jpg" }
    ];

    var id = 2;
    for (var i = 0; i < $scope.bars.length; i++) {
      if ($scope.bars[i].id === id) {
        $scope.bar = $scope.bars[i];
        break;
      }
    }
  })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ViewBarsCtrl">
  Bar: {{bar.title}}
  </div>
&#13;
&#13;
&#13;