Question

I am reading 'Pro AngularJS', there is a demo on 'sportsStore' which has code like this:

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>

when user click a category, selectCategory() is triggered, but why it will make ng-repeat="item in data.products | filter: categoryFilterFn" called? so the products are filtered? I have tried to empty selectCategory()'s implementation, the filter will still be called, why?

Was it helpful?

Solution

AngularJS uses dirtychecking. They actually call every expression to check if the result is different to rerender the view. Angular does this in the so called digest loop. They call this loop every time some variables are chached inside of angular or outside and scope.$apply() is called.

Update

You can use bindonce and scalyr sly to prevent angular from evaluating every expression. In smaller Apps you don't need them, but I used them in large Apps with a great performance improvement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top