Lucky Soni
Lucky Soni

Reputation: 6888

Angular Scope and ng-repeat

My question in short

how do i manipulate the isolated scope created by ng-repeat inside of my controller?

To read the full problem i am having continue reading below:

I have a collection on timelines and each of them further has a collection of captures (essentially images).

HTML

<ul>
    <li ng-repeat="timeline in timelines | filter:search | orderBy:'event_date':sort">
        <ul ng-if="timeline.captures">
            <li ng-repeat="captures in timeline.captures | limitTo:imageLimit">
                <img ng-src="<% captures.capture_location %>">
            </li>
        </ul>
        <a ng-click="(imageLimit = imageLimit + 1)">Load more</a>
    </li>
</ul>
  1. I want to limit the number of images being loaded on page load.. which i am able to do using limitTo

  2. I want to load more images when the user clicks on 'Load more'. I am also able to do this by ng-click="(imageLimit = imageLimit + 1)

What i want to do:

I want to extract this out as a function

so that the following
<a href="#" ng-click="(imageLimit = imageLimit + 1)">Load more</a>
becomes 
<a href="#" ng-click="loadMore()">Load more</a>

To achieve this, i tried the following:

inside my controller

$scope.imageLimit = 1; // number of images to show initially on page load

$scope.loadMore = function() {
    $scope.imageLimit += 1;
};

Now what is happening is that this this not create the imageLimit model inside the repeated scope (if you understand what i mean) but instead creates the imageLimit model at the controller scope. This is also the expected behaviour but i want to know how do i manipulate the scope within the repeated timeline (isolated scope for that timeline) inside my controller?

Upvotes: 0

Views: 286

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

If I understand correctly, you want to be able to loadMore() for each timeline, independantly of the other ones. The loadMore() function should thus take the timeline as argument, and the limit should be a property of the timeline:

angular.forEach($scope.timelines, function(timeline) {
    timeline.imageLimit = 10; // default value
});

$scope.loadMore(timeline) {
    timeline.imageLimit++;
}

And in your template:

<li ng-repeat="captures in timeline.captures | limitTo:timeline.imageLimit">
...
<a ng-click="loadMore(timeline)">Load more</a>

Upvotes: 3

Related Questions