4

I display a list of items through ng-repeat

<div ng-repeat="{item in items}" >
<h3>{{item.name}}</h3>
<h3>{{item.price}}</h3>
<h3>{{item.date}}</h3>
</div>

I have an add where i click and add new items..I display through ng-repeat in a div and that contains scroll..Whenever i add a new item the scroll bar stand still and i can see the newly added item by scrolling down only.

I used ng-focus="{$last}" to set focus on last item but it didnt work.

I need to set focus on last element in ng-repeat even i have 50 elements in div.

Plss help me in this..

Ninja
  • 201
  • 4
  • 16

2 Answers2

5

I'd recommed using a directive to achieve this behaviour.

module.directive('setFocus', function(){
  return{
      scope: {setFocus: '='},
      link: function(scope, element){
         if(scope.setFocus) element[0].focus();             
      }
  };
});

And on your HTML:

<div ng-repeat="{item in items}" set-focus="$last">
    <h3>{{item.name}}</h3>
    <h3>{{item.price}}</h3>
    <h3>{{item.date}}</h3>
</div>

When you load the page, .focus() is ran on the last element.

If you add an element, .focus() is ran on that new last element.

Now your problem lies on which elements are focusable across different browsers. I suggest you check which HTMLElement can receive focus.

So, you may want to add a hidden focusable element inside your div, and modify the directive to focus on that, or maybe add a tabindex attribute to your ng-repeat div. (tabindex="some number other than -1")

<div ng-repeat="{item in items}" set-focus="$last" tabindex="0">
    <h3>{{item.name}}</h3>
    <h3>{{item.price}}</h3>
    <h3>{{item.date}}</h3>
</div>

I hope this helps!

To clarify: ng-focus is used to specify behaviour ON focus, not to trigger focus on the element.

Community
  • 1
  • 1
alejandrociatti
  • 1,122
  • 11
  • 16
1

You can use $anchorScroll in AngularJS. Just place a link (< a> < /a>) at the bottom of your div with the id="bottom" and ng-hide="true", so you dont actually see the link.

<div id="scrollArea" ng-repeat="item in items">
    <h3>{{item.name}}</h3>
    <h3>{{item.price}}</h3>
    <h3>{{item.date}}</h3>
    <a id="bottom"></a>
</div>
<button type="button" ng-click="addNewItem" value="Add"/>

When you click on your "add" button or whatever, call a function in the Controller that leads you to the bottom link with the id="bottom".

$scope.addNewItem = function() {
    //Add new item here...

    //After adding item, go to bottom:
    $location.hash('bottom');
    $anchorScroll();
};

You can read more about this on the Documentaion of AngularJS: Documentaion of $anchorScroll.

lui1000
  • 89
  • 1
  • 6