我正在尝试使用基于函数内部条件的ng-class,但有时切换不起作用。我使用$ scope.getBookmarkIcon函数,这样即使页面刷新后我也可以使用bookmarkIcon类选择ng-class但它不是工作属性。
$scope.bookmarks = $cookieStore.get('data_bookmark') ? $cookieStore.get('data_bookmark') : { items:[] };
console.log($scope.bookmarks);
$scope.saveBookmark = function(resortId) {
$scope.bookmarks.items.push({ id:resortId });
$cookieStore.put('data_bookmark',$scope.bookmarks);
var cookie = $cookieStore.get('data_bookmark');
console.log($scope.bookmarked);
console.log(cookie);
};
$scope.removeBookmark = function(resortId) {
var data = $scope.bookmarks.items;
for(var key in data) {
if(data[key].id===resortId) {
var index = Object.keys(data).indexOf(key);
$scope.bookmarks.items.splice(index, 1); break;
}
}
$cookieStore.put('data_bookmark',$scope.bookmarks);
var ncookie = $cookieStore.get('data_bookmark');
console.log($scope.bookmarked);
console.log(ncookie);
};
$scope.getBookmarkIcon = function(resortId)
{
$scope.bookmarked = false;
var dataList = $scope.bookmarks.items;
dataList.filter(function(item) {
if(item.id===resortId) {
$scope.bookmarked = true;
}
});
return $scope.bookmarked;
};
}]);
这是我到目前为止所尝试的: http://plnkr.co/edit/raZeNb9FdCtfsf6FanU5?p=preview
答案 0 :(得分:0)
最后我解决了我的问题,我想分享。
这是完整的来源:
http://plnkr.co/edit/9NZHjAuEvC6wVN7YE8Yh?p=preview
而不是两个功能,一个用于添加书签,另一个用于删除书签,我用一个切换功能简化了它。
我初始化了 $ scope.bookmarked = false;
然后在html:
<td class="ellipsis" ng-model="bookmarked" ng-class="{'bookmarkIcon':getBookmarkIcon(item)}">
<a ng-click="bookmarked=!bookmarked; toggleBookmark(item);"
href="javascript:void(0);" title="{{(getBookmarkIcon(item))?'Remove
bookmark':'Bookmark this area'}}">{{item}}
</a>
</td>
然后我将getBookmarkIcon(item)保留在model之外,其中只根据cookie中的存储值返回true或false。
var app = angular.module('myCookieBasedBookmark', ['ngCookies']);
app.controller('homeController', ['$cookieStore', '$cookies', '$scope', function($cookieStore, $cookies, $scope) {
$scope.bookmarked = false;
$scope.bookmarks = $cookieStore.get('data_bookmark') ? $cookieStore.get('data_bookmark') : { items:[] };
console.log($scope.bookmarks);
$scope.toggleBookmark = function(resortId) {
var data = $scope.bookmarks.items;
var found = false;
for(var key in data) {
if(data[key].id===resortId) {
var index = Object.keys(data).indexOf(key);
$scope.bookmarks.items.splice(index, 1); found = true; break;
}
}
if(!found){
$scope.bookmarks.items.push({ id:resortId });
}
$cookieStore.put('data_bookmark',$scope.bookmarks);
var cookie = $cookieStore.get('data_bookmark');
console.log(cookie);
};
$scope.getBookmarkIcon = function(resortId) {
var found = false;
var dataList = $scope.bookmarks.items;
dataList.filter(function(item) {
if(item.id===resortId) {
found = true;
}
});
return found;
};
}]);