I'm trying to learn Angular by converting a piece of working jQuery/AJAX code. It's an activity viewer inside a table that basically displays a message with a button to 'Mark Read' or 'Mark Unread' based on the condition. I'm having trouble setting the button text based on activity.seen == 0
.
// html
<div class="table-responsive" ng-controller="Activity">
<table class="table table-bordered table-striped table-hover">
<tbody>
<tr ng-repeat="activity in activities" ng-class="{ 'activity-read': activity.seen == 1 }">
<td><button class="btn btn-default"><span ng-bind="buttonText"></span></button></td>
<td>{{ activity.content }}</td>
</tr>
</table>
</div>
// controller
function Activity($scope, $http, $templateCache)
{
$http.get('/activity/get').success(function(response, status)
{
$scope.activities = response;
angular.forEach($scope.activities, function(activity)
{
$scope.buttonText = activity.seen == 0 ? 'Mark Read' : 'Mark Unread';
});
});
}
This just sets buttonText
to whatever the last value of the activity.seen
conditional was though. So how can I dynamically bind the correct text to each row's button on initial load.
This should have two-way binding I think because I also need update the button text after it's clicked based on the new value of activity.seen
which will be posted to an update method via $http
.
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index . Save this answer.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object.
Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}. {{item}} </div> </div>
I think this should do what you want:
<button ng-click='activity.seen = !activity.seen'>
<span>{{activity.seen ? 'Mark unread' : 'Mark read'}}</span>
</button>
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With