Angularjs:为什么$ watch中的$ scope.variable不是最新的?

时间:2014-03-21 21:07:40

标签: angularjs directive

我创建了一个Plunker here来说明问题。这是主要代码:

<body ng-controller="MainCtrl">
  <table class="table table-bordered table-striped table-condensed table-hover">
      <caption class="text-left" style="background-color: lightgray">
          Search: <input ng-model="searchString" style="width: 80px" />
          Filted count: {{filteredList.length}}
      </caption>
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Sex</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="emp in filteredList = (data.employees | filter:searchString)">
        <td>{{emp.firstName}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.sex}}</td>
      </tr>
    </tbody>
  </table>
</body>

App.js:

$scope.searchString = '';
$scope.$watch('searchString', function(str) {
  console.log($scope.filteredList.length);
});    

问题是filterList.length的console.log总是一个循环(与html相比是正确的),即来自前一个过滤器。我该如何解决?

1 个答案:

答案 0 :(得分:0)

filteredList.length更改后,您正在记录searchString。但是,目前,filteredList中的过滤器尚未修改ngRepeat

解决此问题的一种方法是改为$watch filteredList.length

$scope.$watch(function() {
  return ($scope.filteredList || []).length;
...

<强>更新
我真的很喜欢shaunhusain的评论。他的建议可能更接近你真正想做的事情。

$scope.searchString = '';
// Initialize filteredItems as a copy of data.employees
$scope.filteredItems = angular.copy($scope.data.employees);

// Watch your search string instead and apply filtering using $filter
$scope.$watch(function() {
    return $scope.searchString;
  }, 
  function(str) {
    $scope.filteredItems = $filter('filter')($scope.data.employees, {$: $scope.searchString}, false);
    console.log($scope.filteredItems.length);
  });

然后,您的ngRepeat就是:

  <tr ng-repeat="emp in filteredItems">
    <td>{{emp.firstName}}</td>
    <td>{{emp.lastName}}</td>
    <td>{{emp.sex}}</td>
  </tr>