仅将类添加到 AngularJS 中的特定 ng-repeat [英] Only add class to specific ng-repeat in AngularJS
问题描述
我的应用中有一个类似 Facebook 风格的系统,我想让用户点击时喜欢按钮改变颜色.这是通过添加一个 .active 类来完成的,但我不知道如何让我的 ng-repeat 中的一个项目具有活动类.
这是我的观点:
<div><a ng-click="favourite(data.ID)" class="tab-item" ><i ng-class="{'active': favourited}" class="icon ion-thumbsup" ></i>最喜欢的</a>
ng-click 将请求发送到服务器以存储在数据库中,一旦此请求成功,当控制器中的favourite"变量变为 true 时,ng-class 将类更改为活动:
$scope.favourite = function(dataID){$favourite.favourite(dataID).then(function(data){$scope.favourited = true;});}
这会导致所有收藏按钮都处于活动状态,所以我只是不知道如何使当前按钮处于活动状态.
提前致谢
这是因为您使用的是 $scope.favourited,因为对于所有 ng-repeat,该变量只有一个副本,因此它会更新所有内容.因此,请尝试根据您的要求为单个记录使用一些变量,因为您一次只想将单个记录标记为收藏.
替换
ng-class="{'active': favourited}"
与 ng-class="{'active': data.favourited}"
和
$scope.favourited = true;
与 data.favourited = true;
I have a Facebook style like system in my app and I want to make the like button change colour when the user clicks. This is to be done by adding an .active class, but I cant figure out how to get just the one item in my ng-repeat to have thr active class.
Heres my view:
<div class="list card" ng-repeat="data in array">
<div>
<a ng-click="favourite(data.ID)" class="tab-item" >
<i ng-class="{'active': favourited}" class="icon ion-thumbsup" ></i>
Favourite
</a>
</div>
</div>
The ng-click sends the request to the server to store in the database, and the ng-class changes the class to active when the "favourite" variable from the controller changes to true once this request is sucesfull:
$scope.favourite = function(dataID){
$favourite.favourite(dataID).then(function(data){
$scope.favourited = true;
});
}
This causes all of the favourite buttons to become active, so I just dont know how to make just the current button active.
Thanks in advance
This is because you are using $scope.favourited as there is only single copy of this variable for all ng-repeats, hence it updates for all. So try to use some variable for individual record as per your requirement as you only want to mark a single record as favourite at a time.
Replace
ng-class="{'active': favourited}"
with ng-class="{'active': data.favourited}"
and
$scope.favourited = true;
with data.favourited = true;
这篇关于仅将类添加到 AngularJS 中的特定 ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!