我有一个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
。 最佳答案
您可以在ng-repeat
表达式中使用分配,例如ng-repeat='item in filteredItems = (items | filter:searchTerm)'
注意:在注释中是错误的变体,因为分配的优先级高于管道。
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) {
});
<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>
但似乎在控制器中更好的过滤器:
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();
});
<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>