gpt4 book ai didi

javascript - 为什么在触发非相关函数时调用 ng-repeat?

转载 作者:行者123 更新时间:2023-11-30 17:29:31 24 4
gpt4 key购买 nike

我正在阅读“Pro AngularJS”,“sportsStore”上有一个演示,其代码如下:

productListControllers.coffee

angular.module 'sportsStore'
.controller 'productListCtrl', ($scope, $filter, productListActiveClass) ->
selectedCategory = null

$scope.selectCategory = (category) ->
selectedCategory = category

$scope.categoryFilterFn = (product) ->
selectedCategory == null or product.category == selectedCategory

sportsStore.coffee

angular.module('sportsStore')
.controller 'sportsStoreCtrl', ($scope) ->
$scope.data =
products: [
{ name: "Product #1", description: "A product", category: "Category #1", price: 100 },
{ name: "Product #2", description: "A product", category: "Category #1", price: 110 },
{ name: "Product #3", description: "A product", category: "Category #2", price: 210 },
{ name: "Product #4", description: "A product", category: "Category #3", price: 202 }
]

app.html

<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SPORTS STORE</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="col-xs-3">
<a ng-click="selectCategory()" class="btn btn-block btn-default btn-lg">Home</a>
<a ng-repeat='item in data.products | orderBy:"category" | unique:"category"' class="btn btn-block btn-default btn-lg" ng-click="selectCategory(item)">{{item}}</a>
</div>
<div class="col-xs-8">
<div class="well" ng-repeat="item in data.products | filter: categoryFilterFn">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">
{{item.price | currency}}
</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
</div>
</div>
</body>

当用户点击一个类别时,selectCategory() 被触发,但为什么它会调用 ng-repeat="item in data.products | filter: categoryFilterFn" ?所以产品被过滤了?我已经尝试清空 selectCategory() 的实现,过滤器仍然会被调用,为什么?

最佳答案

AngularJS 使用脏检查。他们实际上调用 every 表达式来检查结果是否不同以重新呈现 View 。Angular 在所谓的摘要循环中执行此操作。每次在 Angular 内部或外部和范围内缓存一些变量时,他们都会调用此循环。调用 $apply()。

更新

您可以使用 bindoncescalyr sly以防止 Angular 评估每个表达式。在较小的应用程序中,您不需要它们,但我在大型应用程序中使用它们,性能得到了很大的改进。

关于javascript - 为什么在触发非相关函数时调用 ng-repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23445632/

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