Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS set button text based on condition in ng-repeat

Tags:

angularjs

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.

like image 403
Jared Eitnier Avatar asked Mar 10 '14 22:03

Jared Eitnier


People also ask

How do you pass an index in NG-repeat?

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.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

What is the use of NG-repeat in AngularJS?

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.

What is $Index in AngularJS?

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>


1 Answers

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

like image 83
Gruff Bunny Avatar answered Oct 09 '22 23:10

Gruff Bunny