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

4

1 回答 1

4

问题是您有href="#",每次单击链接时都会将锚点/滚动位置重置为页面顶部。

我看到两个简单的解决方案:

最简单的是将锚点更改为按钮。这仍然清楚地表明这是一个可点击元素,但没有锚元素:

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

如果您更喜欢锚样式的外观,您可以删除href="#",然后更新您的 CSS 以设置非锚链接的样式,使其看起来像一个链接。像这样的东西:

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

和CSS:

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

这两种解决方案都解决了直接问题,无需任何额外的 JavaScript。

于 2013-08-02T14:42:32.553 回答