无法在ngRepeat中引用过滤后的数组 - AngularJS

时间:2015-07-09 16:55:17

标签: javascript angularjs

我有一个ngRepeat指令,过滤为:

<li ng-repeat='item in items | filter:searchTerm as filteredItems'>{{item.name}}</li>

我想要访问我的控制器中的filteredItems,例如$scope.filteredItems,但我得到了一个未定义的。我该怎么解决这个问题?

我有嵌套控制器。是$scope的问题吗?

我的控制器在我看来是这样的:

<div ng-controller='MainController'>
 <div ng-controller='FilterController'>
  <li ng-repeat='item in items | filter:searchTerm as filteredItems'>{{item.name}}</li>
 </div>
</div>

我正在尝试访问$scope.filteredItems中的FilterController

1 个答案:

答案 0 :(得分:1)

您可以在ng-repeat表达式ng-repeat='item in filteredItems = (items | filter:searchTerm)'中使用分配 注意:在评论中是错误的变体,因为分配的优先级高于管道。

&#13;
&#13;
var appModule = angular.module('app', []);
appModule.controller('MainController', function ($scope) {
    //some functions and variables here
    $scope.items = [
        {name:'1234'},
        {name:'2341'},
        {name:'3412'},
        {name:'4123'},
        {name:'4321'}
    ];
});
appModule.controller('FilterController', function ($scope) {
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
<div ng-app="app" ng-controller='MainController'>
    <div ng-controller='FilterController'>
        <!-- FilterController has many filters that are not related -->
        <input type="text" ng-model="searchTerm" />
        <ul>
            <li ng-repeat='item in filteredItems = (items | filter:searchTerm)'>{{item.name}}</li>
        </ul>
        {{filteredItems}}
    </div>
</div>
&#13;
&#13;
&#13;

但似乎在控制器中有更好的过滤器:

&#13;
&#13;
var appModule = angular.module('app', []);
appModule.controller('MainController', function ($scope) {
    //some functions and variables here
    $scope.items = [
        {name:'1234'},
        {name:'2341'},
        {name:'3412'},
        {name:'4123'},
        {name:'4321'}
    ];
});
appModule.controller('FilterController', function ($scope,$filter) {
    var filter = $filter('filter');
    $scope.filter = function(){
      $scope.filteredItems = filter($scope.items, $scope.searchTerm);
    }
    $scope.filter();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
<div ng-app="app" ng-controller='MainController'>
    <div ng-controller='FilterController'>
        <!-- FilterController has many filters that are not related -->
        <input type="text" ng-model="searchTerm" ng-change="filter()" />
        <ul>
            <li ng-repeat='item in filteredItems'>{{item.name}}</li>
        </ul>
        {{filteredItems}}
    </div>
</div>
&#13;
&#13;
&#13;