【发布时间】:2016-03-31 02:11:37
【问题描述】:
我在我的项目中使用了最喜欢的按钮。这是demo
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 项的心形按钮时,该按钮变为活动状态,当我再次导航到第 2 项的 ItemPage.html 时,该按钮已处于活动状态。在每个项目页面中,我都有 {{object.itemid }} 。我想将 itemid 添加到本地存储中,因此该按钮仅在为每个项目按下按钮时才处于活动状态。我从未使用过本地存储。有什么建议吗?在此先感谢。
【问题讨论】:
-
item2 的 item id 是什么?您的示例似乎工作正常,只要每个项目具有不同的 id 就不会有任何问题
-
当我在 itempage 并查看项目 1 并单击按钮将 item1 设置为收藏时,项目 1 的 itemid=1,item1 的 itemid=2 是有效的。但是,当我返回到 itempage.html 以查看 item2 时,该按钮已经处于活动状态。所以所有项目只有一种状态(活动或非活动)。我需要为每个项目一个状态。