Inside ng-repeat="item in items"I have a wishlist logical button, which can be trueor false.
<div ng-repeat="item in items" ng-controller="ItemCtrl as ctrl">
<md-button class="md-icon-button" ng-click="ctrl.toggleWish(item)">
<i class="material-icons">{{ctrl.hasWished(item) ? 'favorite' : 'favorite_border' }}</i>
</md-button>
</div>
using the function hasWished(item), I check if the current user ID ( Auth._currentUser.id) is within the user IDs stored in the item’s wish list.
The JSON output of one itemlooks simplified as follows:
{"id":1,"title":"This is a tile","wishes":2,"wishlists":[{"user_id":2},{"user_id":3}]}
Therefore, the function hasWished(item)should return trueeither false:
this.hasWished = function(item) {
return item.wishlists.some(function(wishlist) {
return wishlist.user_id === Auth._currentUser.id
});
};
It still works. Using the function, toggleWishI want to switch hasWished(item)from true to false or vice versa:
this.toggleWish = function(item) {
if (!this.hasWished(item)) {
this.hasWished = function(item){return true};
items.wish(item);
item.wishes += 1;
ToastService.show(item.title + ' added to Wish List');
} else {
this.hasWished = function(item){return false};
items.unWish(item);
item.wishes -= 1;
ToastService.show(item.product + ' removed from Wish List');
}
};
toggleWish , items ng-repeat="item in items" true false ( , ). , toggleWish(item).
- hasWished true false - , , ( hasWished).
, !