Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new in angular and I reeding A.Freeman's book "Pro Angular JS". So I stuck in one of examples trying to understand why filter in ng-repeat is triggered. Here is the code:

<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'" ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg">
         {{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>

and

angular.module("sportsStore")
    .controller("productListCtrl", function ($scope, $filter) {
        var selectedCategory = null;
        $scope.selectCategory = function (newCategory) {
            selectedCategory = newCategory;
        }
        $scope.categoryFilterFn = function (product) {
            return selectedCategory == null ||
                product.category == selectedCategory;
        }
    });

categoryFilterFn is one that confuses me. Why it's invoking when I press catefory buttons (with selectCategory() method on ng-click) since I never call categoryFilterFn explicitly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
120 views
Welcome To Ask or Share your Answers For Others

1 Answer

Answering you question - because of $digest. You don't have call categoryFilterFn directly. Your selectedCategory has changed which is used in categoryFilterFn and categoryFilterFn is bound to scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...