I am using angularjs 1 and node js for my project.
Here I am displaying products using ng-repeat.Each product I have an option to share in social networks. I need to get the share count of each so I need to call a function for getting the same. I have tried to call function ng-init but for all products its taking the last product count
Here is my sample code
<div ng-repeat="(key,popc) in product" class="courses-outer-div">
<div class="courses-text-div">
<div class="course-title-div">
{{popc.Title}}
</div><br />
<span class="ash-txt-sml">{{popc.ListFee|currency:"₹":0}}</span><br/>
<div class="common-left pad-top-10"><span class="blue-txt">Share</span><br />
<a target="_blank" href="http://facebook.com/sharer.php?u=url&i=imagurl" target="_blank">
<img src="images/share-fb.png" width="24" height="23" alt="" /></a>
<div ng-init="getfbshare(popc.id)">{{fbcount}}</div>
</div>
</div></div>
Controller.js
$scope.getfbshare = function(id)
{
$http.get('/api/fbcount'+id).then(function(response)
{
alert("f"+response.data.share.share_count)
$scope.fbcount = response.data.share.share_count;
});
};
alert is showing correct value.
Because of ng-repeat
$scope.fbcount
is taking the last value.
Please help me to find out the solution
Your getfbshare
method sets a fixed value on the scope ($scope.fbcount
), which will be overwritten by any subsequent calls to the function.
Instead of passing popc.id
to your function, you can pass the entire popc
object, then, in the response, you can modify the object, like so:
$scope.getfbshare = function(popc)
{
$http.get('/api/fbcount'+popc.id).then(function(response)
{
popc.fbcount = response.data.share.share_count;
});
};
Then, in your view:
<div ng-init="getfbshare(popc)">{{popc.fbcount}}</div>
Ideally you would call that method at a different part of your app lifecycle than with ng-init
.