我正在尝试为我的AngularJS应用创建一个收藏夹按钮。这个想法是当用户点击按钮时,按钮图像改变,让用户知道它选择了专辑作为收藏。我想补充一点,我是框架和Web开发的新手,所以任何反馈和建议都将受到赞赏。
这是我服务的代码:
angular
.module("jeviteca")
.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);
};
}]);
这是我正在使用的指令
angular.module("jeviteca").directive("albumDirectiveTabla", ["FavoriteService", function(FavoriteService) {
return {
restrict: "AE",
templateUrl: "views/AlbumDirectiveTabla.html",
replace: true,
scope: {
model: "="
},
link: function(scope)
{
scope.isLocalStorageEnable = FavoriteService.isLocalStorageEnable;
scope.isFavorite = FavoriteService.isFavorite(scope);
scope.setFav = FavoriteService.setFav(scope);
scope.deleteFav = FavoriteService.deleteFav(scope);
}
};
}]);
这是我的观点 - > html的
<tr>
<td><img ng-src="vendor/resources/img/{{::model.image}}" width="50" height="50" class="img-circle"></td>
<td>{{::model.title}}</td>
<td>{{::model.year}}</td>
<td>{{::model.band.name}}</td>
<td>{{::model.genre.name}}</td>
<td>
<ul>
<li ng-hide="isLocalStorageEnable()"> Local Storage not enabled </li>
<button ng-click="deleteFav()" ng-show="isFavorite()" class="glyphicon glyphicon-heart"></button>
<button ng-click="setFav()" ng-hide="isFavorite()" class="glyphicon glyphicon-heart-empty"></button>
</ul>
</td>
<td ng-repeat="track in model.tracklist">
<ul>
<li>
{{track}}
</li>
</ul>
</td>
</tr>
答案 0 :(得分:1)
首先,我建议您使用https://github.com/grevory/angular-local-storage当localStorage不可用时,它会回退到cookie,因此您无需检查存储是否已启用,因为它将存储在Cookie中。
第二,这个建筑师角度并不知道某些事情发生了变化。
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 true :
FavoriteService.deleteFav(scope);
break;
}
scope.isFavorite = type;
}
}
模板
<button ng-click="markAs(!isFavorite)" class="glyphicon" ng-class="{'glyphicon-heart' : isFavorite , 'glyphicon-heart-empty' : !isFavorite }"></button>
让我知道它的工作原理。