Select 数组中的一项而不是重复

Select one item from array rather than repeat through

当我使用 ng-repeat 时,我循环遍历数组并将其全部吐出,但是我想使用与 soemthign else 相同的数据源并且只有其中之一 selected.

与其使用 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,所以我想 select 适合 BarID 的行,并且能够像我的 html

中的 {{$scope.bar.title}}

您可以遍历条形图,匹配 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}}就好了。


看这里:

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;
      }
    }
  })
<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>