Reputation:
I have a list of items, and on each item I have a button where I can click "Add to favourites" and then a variable should be set to true, and a class is enabled..
in my controller, I've set $scope.isFavourite = false - When clicking a button I set the $scope.isFavourite = true
The problem with this is that all items on the page gets the class
The code here: HTML:
<button ng-click="addToFav()" ng-class="{'active' : isFavourite}"><i class="ion-heart"></i> Netto</button>
And in my controller:
$scope.addToFav = function () {
$ionicPopup.show({
title: 'Tilføj til favoritter',
subTitle: 'Ønsker du at tilføje denne butik til dine favoritter?',
scope: $scope,
buttons: [
{ text: 'Nej' },
{
text: '<b>Ja</b>',
type: 'button-positive',
onTap: function(e) {
$scope.isFavourite = true;
}
}
]
});
};
The problem is that when clicking, it doesn't isolate it to the button you've clicked, but at a global level instead which means that every button in my list gets the class="active", where it only should be the button i've clicked
Upvotes: 1
Views: 4877
Reputation: 1040
By using scope: $scope
you are setting the scope to your surrounding controller scope, so all of your popups sharing the same isFavourite
variable.
You could do something like this:
<div ng-repeat="item in items">
<button ng-click="addToFav(item)" ng-class="{'active' : item.isFavourite}"><i class="ion-heart"></i> Netto</button>
</div>
controller:
$scope.addToFav = function (item) {
$ionicPopup.show({
title: 'Tilføj til favoritter',
subTitle: 'Ønsker du at tilføje denne butik til dine favoritter?',
scope: $scope,
buttons: [
{ text: 'Nej' },
{ text: '<b>Ja</b>',
type: 'button-positive',
onTap: function(e) {
item.isFavourite = true;
}
}
]
});
Working plunker:
http://codepen.io/kbkb/pen/ONzgBQ?editors=1111
Upvotes: 0
Reputation: 2549
You're going to want to look into Angular Components (some documentation can be found here. Basically a component is a reusable piece of code that has it's own scope, so changes made to one component don't affect the others. I would go into more detail, but I don't know Angular as well as I do Angular 2.
Upvotes: 0