Aayush Chadha Aayush Chadha - 1 month ago 8
Javascript Question

How to add data after each iteration of for loop to the app view in Ionic?

I am creating an app that searches for certain words in a dictionary and if the words exist in the dictionary, the definition, along with some other data is outputted to the app view. My problem is, that whenever there is more than one word that is present in the dictionary, the app only outputs the last word found.

Below is the code that does the linear search. (I know this can probably be optimised using binary search, but for now it serves my purpose:

for (var i=0; i < result.length; i++) {
for(var k=0; k <my_dictionary.length; k++){
if(result[i]== my_dictionary[k].word) {
me.word = my_dictionary[k].word;
me.definition = my_dictionary[k].definition;
me.usage = my_dictionary[k].usage;
console.log(me.word);
}
} //looping over words in dictionary
}


Here is the code in the template file that renders these variables:

<h3 class="text-center" ng-show="home_ctrl.word"><u>Word:</u>{{home_ctrl.word}}</h3>
<h3 class="text-center" ng-show="home_ctrl.definition"><u>Explanation:</u>{{home_ctrl.definition}}</h3>
<h3 class="text-center" ng-show="home_ctrl.usage"><u>Usage:</u>{{home_ctrl.usage}}</h3>


Is there some way that each word is outputted to the view as it is found in the dictionary?

Answer

You can create an empty array and push the object result of meObject into the array. Finally, you can use ng-repeat to loop the array in html.

var meArray = [];

for (var i=0; i < result.length; i++) {
    for(var k=0; k <my_dictionary.length; k++){
        if(result[i]== my_dictionary[k].word) {
            var meObject = {
                word: my_dictionary[k].word;
                definition: my_dictionary[k].definition;
                usage: my_dictionary[k].usage;
            }
            me.push(meObject);
        } 
    } //looping over words in dictionary 
}

$scope.home_ctrl_array = meArray;

<div ng-repeat="home_ctrl in home_ctrl_array">
    <h3 class="text-center" ng-show="home_ctrl.word"><u>Word:</u>{{home_ctrl.word}}</h3>
    <h3 class="text-center" ng-show="home_ctrl.definition"><u>Explanation:</u>{{home_ctrl.definition}}</h3>
    <h3 class="text-center" ng-show="home_ctrl.usage"><u>Usage:</u>{{home_ctrl.usage}}</h3>
</div>
Comments