Using Angular JS filters in controllers method 1

by manoj

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="app"> <span class="bold">Demonstrating filtering and sorting using Angular JS</span>

    <br />
    <br />
    <div ng-controller="ShoppingCartCtrl">
        <div>search by:
            <select ng-model="sortExpression">
                <option value="Name">Name</option>
                <option value="Price">Price</option>
                <option value="Quantity">Quantity</option>
            </select>
        </div>
        <br />
        <div>
        </div>
        <table>
            <tr>
                <td>search:</td>
                <td>
                    <input type="text" ng-model="search" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="Apply Sorting/Filtering" data-ng-click="applySortingAndFiltering()">
                </td>
                <td></td>
            </tr>
        </table>
        <br />
            <strong>Filter Results</strong>
        <table border="1">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Quantity</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in items">
                    <td>{{item.Name}}</td>
                    <td>{{item.Price | rupee}}</td>
                    <td>{{item.Quantity}}</td>
                </tr>
            </tbody>
        </table>\
        <br /> <span>Total: {{totalPrice}}</span>

        <br />
    </div>
</div>

JavaScript

var app = angular.module('app', []);

app.controller('ShoppingCartCtrl',

function ($scope, $filter, orderByFilter, filterFilter, rupeeFilter) {
    var items = items = [{
        Name: "Soap",
        Price: 25,
        Quantity: 10
    }, {
        Name: "Shaving cream",
        Price: 50,
        Quantity: 15
    }, {
        Name: "Shampoo",
        Price: 100,
        Quantity: 5
    }];

    var calculateTotalPrice = function () {
        var price = 0;
        for (i = 0; i < $scope.items.length; i++) {
            price += $scope.items[i].Price * $scope.items[i].Quantity;
        }
        $scope.totalPrice = $filter('rupee')(price);
    }

    $scope.items = items;
    calculateTotalPrice();

    $scope.mySortFunction = function (item) {
        if (isNaN(item[$scope.sortExpression])) return item[$scope.sortExpression];
        return "Name";
    }

    $scope.applySortingAndFiltering = function () {
        //$scope.items=$filter('filter')($filter('orderBy')(items,$scope.mySortFunction),$scope.search);
        $scope.items = filterFilter(items, ((items, $scope.mySortFunction), $scope.search));
    }
});

app.filter('rupee', function () {
    return function (item) {
        return "Rs. " + item;
    }
});