UTSAV BHAGAT UTSAV BHAGAT - 5 months ago 21
AngularJS Question

show glyphicon based on value html angular

controller:

.controller('BlogController', function(blogFactory, $routeParams, $scope){

var that=this;

stat=false;

this.checkbookmark = function(bId){
console.log(bId)
blogFactory.checkBookmark(bId, function(response){
console.log(response)
if(response == "bookmarked"){
that.stat = true;
}
else{
that.stat = false;
}
})
}


html code:

<div class="container" ng-controller="BlogController as blogCtrl">

<div class="row" ng-repeat="chunk in blogCtrl.blogs | filter: filter_name | orderBy:'-created_at' | groupBy: 3">


<div class="outerbox1 col-sm-4" ng-repeat="blog in chunk" >
<div class="innerbox3" ng-init="blogCtrl.checkbookmark(blog._id)">
<br>
<div> > READ MORE
<a ng-if="blogCtrl.stat" ng-href="#" ng-click="blogCtrl.removebookmark(blog._id)" class="glyphicon glyphicon-heart pull-right">{{blogCtrl.stat}}</a>
<a ng-if="!blogCtrl.stat" ng-href="#" ng-click="blogCtrl.addbookmark(blog._id)" class="glyphicon glyphicon-heart-empty pull-right">{{blogCtrl.stat}}</a>
</div>

</div>
</div>
</div>
</div>


I want to show glyphicon based on the value of stat

I have 6 blogs, first 3 are bookmarked and next 3 are not.

The problem i'm getting is that the stat value is always set according to the last bookmark and hence it is always false / true (based on the condition of last blog).

How to resolve this?

Answer

Instead of setting the stat property on the controller you should set the property on the blog object (it obviously belongs to the object)

Replace your checkbookmark function with this:

this.checkbookmark = function(blog){ //pass the entire blog, not just the id
    blogFactory.checkBookmark(blog._id, function(response){
        console.log(response)
        if(response == "bookmarked"){
            blog.stat = true;  //set the property on blog instead of the controller
        }
        else{
            blog.stat = false;  
        }
    })
}

And then use it like this:

<div class="innerbox3"  ng-init="blogCtrl.checkbookmark(blog)">
    <br>
    <div> > READ MORE 
        <a ng-if="blog.stat" ng-href="#" ng-click="blogCtrl.removebookmark(blog._id)" class="glyphicon glyphicon-heart pull-right">{{blog.stat}}</a>
        <a ng-if="!blog.stat" ng-href="#" ng-click="blogCtrl.addbookmark(blog._id)" class="glyphicon glyphicon-heart-empty pull-right">{{blog.stat}}</a> 
    </div>
</div>

You will need to make similar changed to your add and removebookmark functions