我想知道在使用AngularJS单击div时如何向HTML元素添加或删除类。我有一个div,当点击时我需要检查它是否包含一个类('已经是成员')。如果该类存在,则将其删除,如果不存在,则添加它。我知道如何在Javascript中执行此操作但在Angular中不确定。
制表members.html
<div collection-repeat="friend in user.friends" item-width="50%" item-height="80px" class="friends-list">
<div class="item friend-avatar" ng-class="{'already-member' : friend.already_member == true}" ng-click="toggleStatus()">
<div class="avatar">
<img src="{{friend.avatar_url}}">
<i class="check-icon" ng-class="{'hidden' : friend.already_member == false}"></i>
</div>
<div class="wrapper-friend-name">
<p class="friend-name">{{friend.name}}</p>
</div>
</div>
</div>
这是controllers.js中的代码
.controller('MembersCtrl', function($scope) {
$scope.members = [
{avatar_url: "http://..."},
{avatar_url: "http://..."},
{avatar_url: "http://..."},
{avatar_url: "http://..."}
];
$scope.user = {
avatar_url: "http://...",
friends: [
{avatar_url: "http://...", name: "Pablo Pepunto", already_member: true},
{avatar_url: "http://...", name: "Pablo Pepunto", already_member: false},
{avatar_url: "http://...", name: "Pablo Pepunto", already_member: false},
{avatar_url: "http://...", name: "Pablo Pepunto", already_member: false}
]
}
$scope.$on('$ionicView.beforeEnter', function (event, viewData) {
viewData.enableBack = true;
});
$scope.toggleStatus = function($scope) {
console.log('$scope'); //$scope is undefined
$scope.classList.toggle('already_member');
$scope.already_member = !$scope.already_member;
}
})
答案 0 :(得分:2)
我会做以下事情:
在模板中:
ng-click="toggleStatus(friend)"
在控制器中:
$scope.toggleStatus = function(friend) {
friend.already_member = !friend.already_member;
}
然后你定义的ng-class="{'hidden' : friend.already_member == false}"
指令应该有效。
答案 1 :(得分:1)
isMember
以设置类。isMember
:ng-class="{'already-member': isMember}"
你也可以像这样直接设置和使用变量:
<div ng-click="isMember = !isMember" ng-class="{'already-member': isMember}">
我建议在控制器中设置标志以提高可读性。