控制器中的AngularJS数据绑定

时间:2014-02-25 18:06:41

标签: 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>

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

2 个答案:

答案 0 :(得分:1)

您可以尝试$观看名称:

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的解决方案可行,但它有点hacky。这种逻辑更好地封装在自定义过滤器中。您可以使用http://docs.angularjs.org/tutorial/step_09中描述的任意逻辑轻松构建一个。

答案 1 :(得分: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>

这是一个有效的方法: http://jsfiddle.net/CAuq9/