When I use an ng-repeat I loop through the array and spit it all out, however I want to use the same datasource as soemthign else and only have one of them selected.
Rather than use ng-repeat and filter to just the one record I assume there must be a better way.
.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" }
];
})
That's my controller. I'vv got BarID coming in through state params so I want to select the row that's right for the BarID and be able to do like {{$scope.bar.title}}
in my html
You can loop through the bars, match the id, and assign that bar to a new variable:
var id = idYouGotFromState;
for (var i = 0; i < $scope.bars.length; i++) {
if ($scope.bars[i].id === id) {
$scope.bar = $scope.bars[i];
break;
}
}
Then you'd be able to use {{bar.title}}
just fine.
See it here:
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>