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

时间:2014-05-03 14:20:23

标签: javascript angularjs angularjs-ng-repeat

我正在阅读'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()的实现,仍会调用过滤器,为什么?

1 个答案:

答案 0 :(得分:2)

AngularJS使用脏检查。他们实际上调用每个表达式来检查结果是否不同以重新呈现视图。 Angular在所谓的摘要循环中执行此操作。每当一些变量被置于角度或外部和范围内时,它们就会调用此循环。$ apply()被调用。

<强>更新

您可以使用bindoncescalyr sly来阻止角度评估每个表达式。 在较小的应用中,您不需要它们,但我在大型应用中使用它们,性能有了很大提升。