简体   繁体   中英

Angular active ng-class isn't working properly

I have some angular code that is supposed to assign a class to only the parent element of the link clicked. This seems to work initially, but then after clicking around a bit, the code seems to get stuck. Here is some sample code of what I'm working with:

<div ng-repeat="item in items track by item.id" class="row" ng-class="{'active': selectItem.this == item.id}">
<a ng-click="selectItem.this = item.id">Move to top</a> {{item.name}}

$scope.selectItem = { this: -1 };

http://plnkr.co/edit/jhahff7OyVTVt615BBp3?p=preview

Any help would be great!

You just need to make the whole text a clickable DOM

<div ng-repeat="item in items track by item.id" class="row" ng-class="{'active': selectItem.this == item.id}">
  <a ng-click="selectItem.this = item.id">Move to top <span ng-bind="item.name"></span></a> 
</div>

I replaced the a tag with p tag and bind an click event to the p tag. With this refactoring, I don't see any lagging or weird behaviour.

<body ng-controller="MainCtrl">
  <div ng-repeat="item in items track by item.id" class="row" 
       ng-class="{'active': selectItem.this == item.id}">
       <p style="cursor: pointer;" ng-click=selectedItem()>
           Move to top {{item.name}}
       </p> 
  </div>
</body>

In controller

$scope.selectItem = {};
$scope.selectedItem = function () {
  $scope.selectItem.this = this.item.id;
};

Let me know if you still see any issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM