控制器中的 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>

上述代码的问题在于数据绑定丢失。当文本字段中的数据发生更改时,不会进行筛选。是否需要为控制器中的输入字段显式设置事件侦听器?谢谢。

您可以尝试$watch名称:

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

有关$watch的更多信息:http://docs.angularjs.org/api/ng/type/$rootScope.Scope。每当通过 Angular 发生"某些事情"时(例如"name"的值会因为您在文本字段中键入某些内容而更改),Angular 将触发您创建的手表并执行该功能。这在这里是必需的,因为您编写的初始代码在实例化控制器时构建 filteredContacts 范围变量,并且不会重新计算此表达式。

虽然这个带有明确$watch的解决方案会起作用,但它有点笨拙。这种逻辑最好封装在自定义筛选器中。您可以使用任意逻辑轻松构建一个,如 http://docs.angularjs.org/tutorial/step_09 中所述。

尝试以下操作

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/

最新更新