returning and calling an object in a list (ANGULAR.js)

前端 未结 3 1422
遥遥无期
遥遥无期 2021-01-22 16:22

in this example I\'m returning a string depending on whether a text field is a value for \"beast\" and/or \"color\". but this is only returning a string. I would return in two c

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 17:04

    You can return objects inside the filter, exactly as you have written them on your question (also, I have cleaned up a bit the ifs... don't use document.getElementById inside the filter, you have the searchText in there already as second parameter of the filter!):

    app.filter('searchData', function() {
      return function(items, searchText) {
        var results = [];
    
        if(searchText) {
    
          angular.forEach(items, function(item) {
            if(item.beast.indexOf(searchText) === 0) {
              results.push({ name: item.beast, type: 'animal' });
            }
    
            if(item.color.indexOf(searchText) === 0) {
              results.push({ name: item.color, type: 'color of animal' });
            }
          });
        }
    
        return results;
      };
    });
    

    And then, you can use this on the P object of the html:

    {{item.name + ' and ' + item.type}}

    I have forked the plunkr here with the changed code:

    http://plnkr.co/edit/EDd578?p=preview

    Hope it helps,

    Best regards,

    Rafa.

    ps. Also, remember always to use the equality operators !== or === in Javascript, and not the != and == forms.

提交回复
热议问题