2015-07-03 58 views
2

当我试图在md-contact-chips上搜索时我有一个错误显示createFilterFor不是函数。但我确实将它创建为一个函数,如下所示。我可否知道有什么方法可以解决这个问题?javascript array.filter()的功能不起作用

基本上我试图克隆这个demo但不是写联系人从我的数据库通过使用HTTP调用来替换联系人名称,即显示以下Account.getTastes()但是手动的名字我叫现有的数据,之后我得到的数据显示在像以下图片那样的md-contact-chip中,querySearch不再工作。 enter image description here

HTML

<md-contact-chips required ng-model="tags" md-require-match md-contacts="querySearch($query)" md-contact-name="name" md-contact-image="image" filter-selected="true" placeholder="Thai, chinese, cheap, cafe and etc"> 
</md-contact-chips> 

Controller.js

$scope.querySearch = querySearch; 
$scope.filterSelected = true; 
$scope.allContacts = loadContacts(); 
$scope.allContacts.then(function(contacts){ 
    $scope.tags = [contacts[0],contacts[1]] 
}) 

    /** 
    * Search for contacts. 
    */ 
    function querySearch (query) { 
     var results = query ? 
      $scope.allContacts.filter(createFilterFor(query)) : []; 
     return results; 
    } 
    /** 
    * Create filter function for a query string 
    */ 
    function createFilterFor(query) { 
     var lowercaseQuery = angular.lowercase(query); 
     return function filterFn(contact) { 
     return (contact._lowername.indexOf(lowercaseQuery) != -1);; 
     }; 
    } 

    function loadContacts() { 
     var contacts; 
     return Account.getTastes() 
      .then(function(res) { 
      contacts = res.data[0].tastes; 
      return contacts.map(function (c, index) { 
       var colors = ["1abc9c", "16a085", "f1c40f", "f39c12", "2ecc71", "27ae60", "e67e22","d35400","3498db","2980b9","e74c3c","c0392b","9b59b6","8e44ad","34495e","2c3e50"]; 
       var color = colors[Math.floor(Math.random() * colors.length)]; 
       var cParts = c.split(' '); 
       var contact = { 
       name: c, 
       image: "http://dummyimage.com/50x50/"+color+"/f7f7f7.png&text="+c.charAt(0) 
       }; 
       contact._lowername = contact.name.toLowerCase(); 
       return contact; 
      }); 
      }) 
      .catch(function(error) { 
       console.log("Error:"+error) 
      }); 
    } 
+0

你可以试试'的​​console.log(createFilterFor);前'VAR的结果= ...''对不对? –

+0

@BaliBalo返回功能createFilterFor(查询) –

+0

嗯,我尝试了[简体版](https://jsfiddle.net/t8bm4rxk/)和它的作品所以它可能是你覆盖'createFilterFor'的东西,是不是函数在你的代码中的某处。只是看到这部分,无法帮助你。 –

回答

1

我已经解决了这个问题

我是不断收到此错误的原因是因为我的$ scope.allContacts是一个promise而不是数组s o .filter将返回错误,说createFilterFor不是一个函数。

$scope.allTastes.then(function(tastes){ 
    $scope.tags = [tastes[0],tastes[1]] 
    $scope.allTags = tastes; // create a new $scope to get all tags from the promise 
}) 

    /** 
    * Search for contacts. 
    */ 
    function querySearch (query) { 
     console.log($scope.allTastes) // return a promise 
     $scope.allTastes= $scope.allTags; // pass it to $scope.allTastes, now it has all the array 
     var results = query ? 
      $scope.allTastes.filter(createFilterFor(query)) : []; 
     return results; 

    } 

感谢您的帮助!