1

i have a list of teams and user can add a team to list of teams. the problem i having is that when i add an item to an list, angular re-renders the list and scroll position is reset to the top.

this is the template

 <div ng-controller="scores">
  <ul>
    <li ng-repeat="team in teams">
      {{team.name}}: 
      <button ng-click="decr(team)">-</button>
      {{team.score}}
      <button ng-click="incr(team)">+</button>
    </li>
  </ul>
    <a href="#" ng-click="add()">(+)Add Team</a>
  </div>

here is the controller code

function scores($scope){
  $scope.teams = [
    {name:'red', score:100},
    {name:'blue', score:100},
    {name:'green', score:100}
  ];

  $scope.decr= function(team){team.score-=1;};
  $scope.incr= function(team){team.score+=1;};  
  $scope.add= function(){$scope.teams.push({name:"...", score:100});};    

}

you can see working example here. http://jsbin.com/asedib/5

1 Answer 1

4

The problem is that you have href="#", which resets the anchor / scroll position to the top of the page every time you click the link.

I see two easy solutions:

The easiest is to change the anchor to a button. This still makes it clear that this is a clickable element, but without the anchor element:

<button ng-click="add()">(+) Add Team</button>

If you prefer the anchor-style appearance, you can remove the href="#", but then update your CSS to style the non-anchor link to look like a link. Something like this:

<a ng-click="add()" class="clickable">(+) Add Team</a>

And the CSS:

a, a.clickable {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}

Both of these solutions solve the immediate problem without any extra JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

Great. button and anchor without href="#", both solves the problem. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.