Celfred Celfred - 1 month ago 6
AngularJS Question

Coming back to init state after ng-click in ng-repeat?

I'm facing an issue due to my very low understanding of basic AngularJs concepts (I think). I have a list of clickable words. When I click on them, they change color (individually) through the use of Bootstrap 'labels' classes. It works fine BUT... (here it is :) ) : If I click my 'Try again' button, I am unable to set my colors back to the init state because I am unable to set 'this.selected' to 'false'... See the below code.

I'm sure it's not that difficult, but I'm stuck so if anyone could give me a hint, I'd appreciate.

<h2 class="jumbleW inline" ng-repeat="w in word track by $index">
<span ng-class="{'label': true, 'label-primary': !this.selected, 'label-warning': this.selected}" ng-click="pickWord(w)">{{w}}</span>
</h2>

<button class="btn btn-danger btn-xs" ng-click="clear()">Try again</button>


EDIT : Sorry for my beginner's mistakes. I accepted the edition of the above code (bare HTML).
Here's also my pickWord() function() :

$scope.pickWord = function(w){
this.selected = !this.selected;
if (this.selected == false) {
$scope.playerAnswer = $scope.playerAnswer.replace(w, "");
} else {
$scope.playerAnswer += w;
}
}

Answer

Don't use this. Instead, either add a property to the ng-repeat object w if its an object otherwise create an array for selected index as below.

html

    <h2 class="jumbleW inline" ng-repeat="w in word track by $index">
      <span ng-class="{'label': true, 'label-primary': selectedItems.indexOf($index) === -1, 'label-warning': selectedItems.indexOf($index) !== -1}" ng-click="pickWord(w, $index)">{{w}}</span>
    </h2>

<button class="btn btn-danger btn-xs" ng-click="clear()">Try again</button>

JS

$scope.pickWord = function(w, i){
    if(!$scope.selectedItems){
       $scope.selectedItems = [];
    }

    var index = $scope.selectedItems.indexOf(i);

    if(index === -1) {   // not selected already and add
       $scope.selectedItems.push(i);
        $scope.playerAnswer += w;
    } else {   // selected already and remove
       $scope.selectedItems.splice(index, 1);
       $scope.playerAnswer = $scope.playerAnswer.replace(w, "");
    }
}

$scope.clear = function(){
   $scope.selectedItems = [];
};
Comments