jwong
jwong

Reputation: 358

Have trouble understanding some code in AngularJS

I'm learning AngularJS by following a book but I'm stuck at some lines of code which are hardly explained in the book.

So this selectCategory() function is included in the ng-click directive

<a ng-click="selectCategory()">Home</a>

<a ng-repeat="item in data.products | orderBy:'category' | unique:'category'"
   ng-click="selectCategory(item)">

   {{item}}

</a>

and also here's the filter which is used to filter the listing products based on their categories when the ng-click directive is triggered

ng-repeat="item in data.products | filter:categoryFilterFn">

those two are defined as follows:

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;
    }
});

I've already spent a lot of time trying to understand those code but I'm still pretty confused, especially about how the two functions are defined. Why $filter is also included in the argument? And also can you explain those definitions please, I'm really lost. Forgive me for being a newbie and many thanks!!

Upvotes: 0

Views: 138

Answers (1)

Christina
Christina

Reputation: 1126

This is a really bad example !!

It should be :

<a ng-click="selectCategory()">Home</a>

<a ng-repeat="item in data.products | orderBy:'category' | unique:'category'"
   ng-click="selectCategory(item.category)">

   {{item.category}}

</a>

So here you choose a category from the available categories (unique categories of products), then products that have this categories are listed (ng-repeat="item in data.products | filter:categoryFilterFn>)

categoryFilterFn is a filter function, so products having category == selectedCategory are listed, and if no selectedCategory all products are listed :)

Hope this helps

Upvotes: 1

Related Questions