Angular ng-repeat images with caption only for 2 of them

797 views Asked by At

I'm using ng-repeat to bind image from a directive (same as we usually make stars rating). In my case I have images, some of them should have caption, not all. Is there a way to make a condition, which will show a caption for second and last images only? without creating an array for all images

My html:

<ul class="qty">
<li ng-repeat="image in imagesArray">
    <img ng-model="imgUrl" ng-src="{{imgUrl}}">
    <div>caption</div>
</li>

My app:

var myDirectives = (function () {
var myDirectives = angular.module('myDirectives', []);
myDirectives.directive('myImages', function () {
    return {
        restrict: 'A',
        scope: {
            qty: '='
        },
        link: function ($scope) {
            $scope.imgUrl = "http://farm6.staticflickr.com/5579/14671096893_806ec359b7_m.jpg";
            $scope.imagesArray = [];
            for (var i = 0; i < $scope.qty; i++) {
                $scope.imagesArray.push({});
            }
        },
        templateUrl: function () { return 'stars.html' },
    }
});
return myDirectives; }());

Plunkr: http://plnkr.co/edit/IdXaRDB9INZlZbWSTmam?p=preview

2

There are 2 answers

1
Giovani Vercauteren On BEST ANSWER

Yes, you can use $last and $first.

Consult the ngRepeat documentation for more information about it.

<ul class="qty">
<li ng-repeat="image in imagesArray">
    <img ng-model="imgUrl" ng-src="{{imgUrl}}">
    <div ng-if="$first || $last">caption</div>
</li>
3
Ram_T On

Done, see my answer. It's working fine

<ul class="qty">
    <li ng-repeat="image in imagesArray track by $index">
        <img ng-model="imgUrl" ng-src="{{imgUrl}}">
        <div ng-if="$index===1 || $last">caption</div>
    </li>
</ul>