如何在angularjs中从控制器访问我的过滤数组?

时间:2022-04-03 09:02:25

I have this expression in the view:

我在视图中有这个表达式:

<div ng-repeat="friend in (filtered = (friendsData | matchnames:search.pattern)) | myLimitTo : 9 : pageIndex * 9"" >

I do the filtered so i can show something like this

我做了过滤,所以我可以显示这样的东西

{{filtered.length}} 

in the view which works great, but how can i access this param in the controller so i do stuff with it?

在视图中工作得很好,但是如何在控制器中访问此参数,以便我用它做什么呢?

1 个解决方案

#1


4  

You can't access $scope.filtered because ng-repeat creates a new scope and sets filtered to it.

您无法访问$ scope.filtered,因为ng-repeat会创建一个新范围并对其进行过滤。

Technically you can create $scope.viewData = {} in your controller and use the following code in the template:

从技术上讲,您可以在控制器中创建$ scope.viewData = {}并在模板中使用以下代码:

<div ng-repeat="friend in (viewData.filtered = (friendsData | matchnames:search.pattern)) | myLimitTo : 9 : pageIndex * 9"" >

There are some other possible ways to do the similar thing: eg if you use controllerAs you could set filtered array to it.

还有一些其他可能的方法来做类似的事情:例如,如果你使用控制器,你可以设置过滤数组。

But in general all these tricks are not very good practice because you want to pass variable implicitly to controller and your angular expression looks quite complex.

但总的来说,所有这些技巧都不是很好的练习,因为你想隐式地将变量传递给控制器​​,你的角度表达看起来很复杂。

#1


4  

You can't access $scope.filtered because ng-repeat creates a new scope and sets filtered to it.

您无法访问$ scope.filtered,因为ng-repeat会创建一个新范围并对其进行过滤。

Technically you can create $scope.viewData = {} in your controller and use the following code in the template:

从技术上讲,您可以在控制器中创建$ scope.viewData = {}并在模板中使用以下代码:

<div ng-repeat="friend in (viewData.filtered = (friendsData | matchnames:search.pattern)) | myLimitTo : 9 : pageIndex * 9"" >

There are some other possible ways to do the similar thing: eg if you use controllerAs you could set filtered array to it.

还有一些其他可能的方法来做类似的事情:例如,如果你使用控制器,你可以设置过滤数组。

But in general all these tricks are not very good practice because you want to pass variable implicitly to controller and your angular expression looks quite complex.

但总的来说,所有这些技巧都不是很好的练习,因为你想隐式地将变量传递给控制器​​,你的角度表达看起来很复杂。