2016-03-30 80 views
0

我在我的项目中使用了最喜欢的按钮。这里是一个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建议?谢谢先进。

+0

什么是项目ID为ITEM2?您的示例似乎工作正常,只要每个项目具有不同的ID,就不应该有任何问题 – S4beR

+0

项目1有itemid = 1,item1有itemid = 2当我在itempage并查看项目1并单击按钮将item1设置为收藏即可使用。但是,当我回到ang时,请转到itempage.html以查看item2,此按钮已处于活动状态。所以所有项目只有一个状态(活动或不活动)。我需要每个项目的一个状态。 –

回答

0

安东尼,

角服务是单身,因此通过应用程序的生命周期被实例化一次。这意味着它们非常适合跨控制器存储和共享数据。

本地存储

The localStorage object店无到期日的数据。浏览器关闭时数据不会被删除,并且将在第二天,一周或一年内提供。

因此,行为。打开多个网页将访问相同的本地存储,本身是一个单身。

区别在于,使用角度,每个打开的页面都有自己的应用程序实例。因此,每个网页都会拥有自己的服务实例。

解决方案

Here is the plunker

守则

angular.module("MyApp").service("FavoriteService",[function(){ 


    this.fav = 0; 

    //Favorites functions 
    this.isLocalStorageEnable = function() { 

     if(typeof (Storage) !== "undefined"){ 
      return true; 
     } 
     else{ 
      return false; 
     } 
    }; 

    this.isFavorite = function(scope){ 
     return this.fav === 1; 
    }; 

    this.setFav = function(){ 
     this.fav = 1; 

    }; 

    this.resetFav = function(){ 
     this.fav = 0; 

    }; 

}]); 
+0

谢谢你的回答。这个解决方案没有解决问题。我已经有同样的问题(该按钮在所有页面中都处于活动状态),现在该按钮处于活动状态,并且再次单击时保持活动状态。 –

+0

我在Chrome中使用了plunker,它的功能就像一个魅力。你是否使用这个plunker:http://plnkr.co/edit/MdtaYFTIKdiFz4csTF5O?p=preview –

+0

是的。当我点击按钮变为活动,然后是所有项目的活跃 –