Ajv2324
Ajv2324

Reputation: 522

Access a ng-repeat variable in a controller

Here is what I currently have:

HTML

            <center><li ng-repeat = "x in items | orderBy: 'priority'"> 
            <!-- color code priorities -->
            <span ng-style="cmplt" ng-class="{ red: x.type == 'Work', blue: x.type == 'Personal' }">
                <b>{{ x.name }}</b></span>
            <span ng-class="{ yourChore: x.assignedTo == username} ">
                - {{ x.type }} (Priority {{ x.priority }}) Assigned by {{ x.creator }} to {{ x.assignedTo }}
            </span>&nbsp;&nbsp;

 <!-- When task is completed, user can click this button to mark it as such -->
            <button type="button" ng-click="cmplt={color: 'gray', 'text-decoration': 'line-through'} ; 
                markAs(this)">Completed</button>
            <div ng-class="{ red: x.completed == true }"> Hello</div>
            <button type="button" ng-click = "comment = true">Comment</button>
            <div ng-show="comment"><textarea rows="3" columns="50" ng-model="x.comments"></textarea></div>
            <div>{{ x.comments }}</div>
        </li></center>

JavaScript

    $scope.markAs = function(repeatScope){
    if (!repeatScope.completed){
        repeatScope.completed = true;
    }
    else {
        repeatScope.completed = false;
    }
};

The object that is being repeated has a boolean value in it that by default is marked false, but when a button is clicked should re-evaluate to true. The problem is this doesn't happen (stays false) and I'm not sure why based off of my code.

Upvotes: 0

Views: 167

Answers (3)

Zee
Zee

Reputation: 8488

You need to pass x which is the current item in your ng-repeat and not this.

<button type="button" ng-click="cmplt={color: 'gray', 'text-decoration': 'line-through'} ; 
            markAs(x)">Completed</button>

Upvotes: 1

devqon
devqon

Reputation: 13997

You can pass in the current element by what you defined in the ng-repeat:

<li ng-repeat="x in items"> <!-- reference to x within the repeat scope -->
    <button type="button" 
            ng-click="cmplt={color: 'gray', 'text-decoration': 'line-through'}; markAs(x)">
        Completed
    </button>
</li>

Upvotes: 3

Okazari
Okazari

Reputation: 4597

The solution is pretty simple, try something like this :

As you used

ng-repeat = "x in items"

x will reference each repeated item.

markAs(x)

Will launch the function with the "right" x in parameters.

Upvotes: 1

Related Questions