User7723337
User7723337

Reputation: 12018

Angular Scroll to specific item in the list created using ng-repeat

In my AngularJS app I have two lists created using ng-repeat.

List one lists all the food categories like:

Meat, Fruits, Vegetables, Poultry, Dry Fruits ... etc.  

List two lists all the foods like:

Eggs, Chicken, Oranges, Apple, Banana ... etc.  

List number two lists food items in groups like, all the Meat items first and then all Fruits.

I have created both of these lists using div and ng-repeat, in one page.
Each element in the both of the lists has unique ID.

What I want to achieve:

When user select one of the food category from list one, then list two should scroll to that particular category related food items.

For example if user selects Fruits in list one then, list two should scroll to Oranges item.

UPDATE

Also is it possible to select item in list one when user scrolls to specific group? For example if user scrolls to Chicken in list two then in list one Meat should be selected.

Upvotes: 1

Views: 6793

Answers (2)

gyc
gyc

Reputation: 4360

I personnally would use Angular's $anchorScroll

    this.scrollTo = function(id) {
        $anchorScroll(id);
    }

Fiddle

Upvotes: 3

jmunsch
jmunsch

Reputation: 24149

What about something like this for a list1 item:

<div ng-repeat="itemType in itemTypes">
  <li ng-click="$scope.scrollThere({{"."+itemType}})">{{itemType}}</li>
</div>

With something like this for list2:

<div id="list2" style="overflow-y: scroll; height: 30px;" ng-repeat="item2 in theItems">
  <li class="{{item2.itemType}}">{{item2.itemName}}</li>
</div>

And then keep track of which element to scroll to somehow like this just goes to the next item in the fruits when fruit is clicked?:

$scope.scrollThere = scrollThere;
$scope.count = { fruit: 0 };
function scrollThere(foodType){
    angular.element('#list2').animate({
      scrollTop: angular.element(foodType)[count[foodType]++].offset().top
    }, 1000);
}

And making sure the y overflow is set to scroll in the css.

Or instead of keeping count with an object you could embed the index logic into an id using "#" + {{itemType}} + $index as the selector on the list1 item.

Upvotes: 2

Related Questions