2015-11-04 241 views
1

我有一个表单,我希望用户能够以搜索条件输入到文本框中,然后单击按钮以搜索列表。用ng-repeat和点击按钮可以做到这样吗?我对Angular非常陌生,我不确定我是否可以将它用于这种类型的功能。我的代码一点点:AngularJS搜索按钮点击

HTML

<div>  
<input ng-model="filterSearch.address" /> 
<input ng-model="filterSearch.city" /> 
<button ng-click="">Search</button>  
<table> 
    <thead> 
     <tr> 
      <th> 
       Address 
      </th> 
      <th> 
       City 
      </th> 
     </tr>    
    </thead> 
    <tbody>    
     <tr ng-repeat="search in vm.searches | filter: filterSearch"> 
      <td> 
       {{ search.address }} 
      </td> 
      <td> 
       {{ search.city }} 
      </td> 
     </tr> 
    </tbody> 
</table> 

控制器:

(function() { 
'use strict' 
angular 
    .module('crm.ma') 
    .controller('AdvancedSearchCtrl', AdvancedSearchCtrl); 

function AdvancedSearchCtrl() { 
    var vm = this; 
    vm.searches = [ 
       { 
        "address": "202 This St", 
        "city": "Columbus" 
       }, 
       { 
        "address": "205 That St", 
        "city": "Dayton" 
       } 

    ]; 


} 
})(); 

如果任何人都可以点我这将是伟大正确的方向。谢谢。

更新代码:

<div>  
<input ng-model="searchModel.address" /> 
<input ng-model="searchModel.city" /> 
<button ng-click="filterSearch = searchModel">Search</button>  
<table> 
    <thead> 
     <tr> 
      <th> 
       Address 
      </th> 
      <th> 
       City 
      </th> 
     </tr>    
    </thead> 
    <tbody>    
     <tr ng-repeat="search in vm.searches | filter:{'address': filterSearch.address, 'city': filterSearch.city}"> 
      <td> 
       {{ search.address }} 
      </td> 
      <td> 
       {{ search.city }} 
      </td> 
     </tr> 
    </tbody> 
</table> 

回答

1

您可以指定字段进行搜索像:

<tr ng-repeat="search in vm.searches | filter:{'address': filterSearch.address, 'city': filterSearch.city"> 
     <td> 
      {{ search.address }} 
     </td> 
     <td> 
      {{ search.city }} 
     </td> 
    </tr> 

如果你需要上点击触发搜索,你可以使用类似的东西:

ng-click="filterSearch = searchModel" 

并更改您的输入以使用searchModel变量。

+0

好的。我在我的问题中更新了我的代码,以反映您提出的更改。虽然我做错了什么,因为当我在文本框中键入它时仍然在搜索列表,而不是在单击按钮时搜索和显示。谢谢你的帮助。 – hollyquinn

+0

你能告诉我一些代码吗?我不知道如何做到这一点? – hollyquinn

+0

如果只是在第一次点击后才发生,那是因为filterSearch对象是通过引用searchModel对象来设置的,而不是被复制的值。只要做'filterSearch = angular.copy(searchModel)' –