Jared Eitnier
Jared Eitnier

Reputation: 7152

AngularJS set button text based on condition in ng-repeat

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.

Upvotes: 18

Views: 28554

Answers (1)

Gruff Bunny
Gruff Bunny

Reputation: 27986

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

Upvotes: 65

Related Questions