返回并调用列表中的对象(ANGULAR.js)

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

本文关键字:ANGULAR js 对象 调用 列表 返回      更新时间:2023-09-26

在这个例子中,我返回一个字符串,这取决于文本字段是"beast"和/或"color"的值。但这只是返回一个字符串。我会在两个有对象的条件下返回:

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

在第一个条件中,我需要创建一个对象并返回:

{name: item.beast, type: "animal"}

在第二个条件中,我需要创建一个对象和:

{name: item.color, type: "color of animal"}

然后在HTML文件中,我可以放一个列表吗:

{{ item.name }} and {{item.type}}

因此,如果我键入"r"应该出现在列表中:

"rat and animal"
"red and color of animal "

我不确定你想要得到什么。看看这个混蛋。这是你想要的吗?

如果你把整个项目推到结果列表中,它就会起作用,比如:

results.push(item);

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

看看这个

 app.service('myFactoryService', function(){
  this.createObj = function(name,type){
    var obj = {};
    obj.name = name;
    obj.type = type;
    return obj;
  }
});
results.push(myFactoryService.createObj(item.beast,"animal"));

我不知道为什么双向绑定不允许以不同的方式显示两个变量,只有对象,但有定义的服务来创建对象,然后根据这两个选项在过滤器中创建。

你可以在过滤器中返回对象,就像你在问题上写的一样(此外,我已经清理了一些if…不要在过滤器中使用document.getElementById,你已经在那里有searchText作为过滤器的第二个参数了!):

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;
  };
});

然后,你可以在html:的p对象上使用这个

<p ng-repeat = "item in data | searchData : search">{{item.name + ' and ' + item.type}}</p>

我在这里用更改后的代码分叉了plunkr:

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

希望有帮助,

致问候,

拉法。

ps。此外,请记住始终使用相等运算符!==或===在Javascript中,而不是!=和==形式。