2014-02-25 56 views
0

結合這個偉大的工程:AngularJS數據控制器

<input type="text" class="search" data-ng-model="name"/> 
<div class="rf-contact" data-ng-repeat="contact in contacts | filter: name"> 
    <p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p> 
</div> 

不過,我需要在控制器來實現過濾器:

var contactsController = function ($scope, $filter){ 
    $scope.contacts = contacts; 
    $scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name); 
} 

<input type="text" class="search" data-ng-model="name"/> 
<div class="rf-contact" data-ng-repeat="contact in filteredContacts"> 
    <p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p> 
</div> 

與上面的代碼的問題是,數據綁定丟失。當文本字段中的數據發生更改時,不會發生過濾。我是否需要爲控制器中的輸入字段顯式設置事件偵聽器?謝謝。

回答

1

你可以嘗試$看-ING名稱:

var contactsController = function ($scope, $filter){ 
    $scope.contacts = contacts; 
    $scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name); 
    $scope.$watch('name', function(newValue, oldValue) { 
     $scope.filteredContacts = $filter('filter')($scope.contacts, newValue); 
    }); 
} 

有關$表的詳細信息:http://docs.angularjs.org/api/ng/type/$rootScope.Scope。任何時候,通過Angular發生「某些事情」(如「name」的值因爲在文本字段中鍵入內容而發生變化),Angular會觸發您創建的手錶並執行該功能。這是必要的,因爲當控制器被實例化時,你編寫的初始代碼會生成filteredContacts範圍變量,並且沒有什麼重新評估該表達式。

雖然這個解決方案具有明確的$ watch功能,但它有點冒險。這種邏輯更好地封裝在自定義過濾器中。您可以使用http://docs.angularjs.org/tutorial/step_09中描述的仲裁邏輯輕鬆構建一個邏輯。

0

請嘗試以下

var contactsController = function ($scope, $filter){ 
    $scope.filterContacts = function(){ 
    $scope.contacts = contacts; 
    $scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name); 
    } 
} 

<input type="text" class="search" data-ng-model="name" ng-change="filterContacts()"/> 
<div class="rf-contact" data-ng-repeat="contact in filteredContacts"> 
    <p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p> 
</div> 

下面是這個動作一的jsfiddle: http://jsfiddle.net/CAuq9/