gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:36:19 26 4
gpt4 key购买 nike

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

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

我试图像 $scope.filteredItems 一样访问 Controller 中的 filteredItems ,但我得到了一个未定义的信息。我该如何解决这个问题?

我有嵌套 Controller 。是$scope有问题吗?

在我看来,我的 Controller 是这样的:

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

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

最佳答案

您可以在 ng-repeat 表达式中使用赋值,例如 ng-repeat='item infilteredItems = (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>

但 Controller 中的过滤器似乎更好:

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>

关于javascript - 无法在 ngRepeat 中引用过滤数组 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31323790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com