My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have already been added to the new list by giving them a different color.
To achieve this, I utilize a function in my controller that uses angular.foreach to compare the two lists. If wordFromQuery._id === wordOnNewList._id, I change the background color of the word using ng-style.
Below is the code snippet:
View
ng-repeat="word in searchWords" ng-click="addWordToSet(word)" ng-class="isInside(word)" ng-style="{ background: choosenWords.value == 'exist' ? 'lightgreen' : 'white' }"
I iterate over the words in the query (searchWords) and add them to the second array using addWordtoSet(word) function. The isInside(word) function performs the comparison between the arrays, while ng-style applies different styles based on the outcome of the isInside function.
Controller
$scope.isInside = function (word) {
angular.forEach($scope.currentWordlist, function (item) {
if (item._id === word._id) {
$scope.choosenWords = {value: 'exist'};
} else {
$scope.choosenWords = {value: 'notOnList'};
}
});
};
The angular.forEach method compares the words in both arrays. currentWordList is where I store the words added using addWordToSet function.
Currently, one word in the searchword array receives the green color when clicked (and the next word will be highlighted as well). It seems like there might be an issue with how I'm using ng-class, but I haven't found a better alternative for accessing the word._id. Can someone point out any obvious mistakes in my approach?
If anyone has any tips or suggestions, I would greatly appreciate it. Thank you!
UPDATE
The addWordToSet function works as intended:
$scope.addWordToSet = function (word) {
var exists = false;
angular.forEach($scope.currentWordlist, function (item) {
if (item._id === word._id) {
exists = true;
}
});
if (!exists) {
$scope.currentWordlist.push(word);
}
};
My only concern now is triggering this behavior without requiring a click. Is my ng-class="isInside(word)"
suitable for achieving this automatic update?