我在我的项目中使用了最喜欢的按钮。这里是一个demo将ID保存到本地存储中,并使用按钮angularjs
的script.js
angular.module("MyApp",[]);
service.js
angular
.module("MyApp")
.service("FavoriteService",[function(){
//Favorites functions
this.isLocalStorageEnable = function() {
if(typeof (Storage) !== "undefined"){
return true;
}
else{
return false;
}
};
this.isFavorite = function(scope){
var fav = localStorage.getItem(scope.id);
return fav === "1";
};
this.setFav = function(scope){
localStorage.setItem(scope.id,"1");
};
this.deleteFav = function(scope){
localStorage.removeItem(scope.id);
};
}]);
directive.js
angular.module("MyApp").directive("albumDirective", ["FavoriteService", function(FavoriteService) {
return {
restrict: "AE",
templateUrl: "AlbumDirective.html",
replace: true,
scope: {
id: "=albumId"
},
link: function(scope)
{
scope.isLocalStorageEnable = FavoriteService.isLocalStorageEnable;
scope.isFavorite = FavoriteService.isFavorite(scope);
scope.markAs = function(type) {
switch(type) {
case true :
FavoriteService.setFav(scope);
break;
case false :
FavoriteService.deleteFav(scope);
break;
}
scope.isFavorite = type;
}
}
};
}]);
AlbumDirective.html
<button ng-click="markAs(!isFavorite)" ><i class="fa" ng-class="{'fa-heart' : isFavorite , 'fa-heart-o' : !isFavorite }"></i></button>
Itempage.html
<album-directive album-id="1"></album-directive>
当我点击按钮心脏在ItemPage.html项目1按钮被激活,当我再次导航到ItemPage.html项目2按钮已经active.In每个项目页面我都有{{object.itemid}}。我想将itemid添加到本地存储中,因此只有当按钮按下每个项目时,按钮才会处于活动状态。我从来没有使用本地storage.Any建议?谢谢先进。
什么是项目ID为ITEM2?您的示例似乎工作正常,只要每个项目具有不同的ID,就不应该有任何问题 – S4beR
项目1有itemid = 1,item1有itemid = 2当我在itempage并查看项目1并单击按钮将item1设置为收藏即可使用。但是,当我回到ang时,请转到itempage.html以查看item2,此按钮已处于活动状态。所以所有项目只有一个状态(活动或不活动)。我需要每个项目的一个状态。 –