Shaohao
Shaohao

Reputation: 3511

Angular Directive with Reset functionality

I have a directive called filterButton, which will let user to select the filter option and add the check mark on the right. Now I have a reset button in filter.html. Once the user click the reset button, all the filter field will set back to default. I had tried couple methods, it didn't work. Any suggestion? Thank you in advance.

app.js

app.directive('filterButton', function () {
return {
        restrict: 'EA',
        templateUrl: 'template/filter-button.html',
        replace: true,
        scope: {
                list: '=', //two-way binding
                selected: '=', //two-way binding
                field: '@', //one-way binding
        },
        link: function ($scope) {
            $scope.selected = [];
            $scope.setSelectedOption = function() {
                var id = this.option.id;

                if(_.contains($scope.selected, id)) {
                    $scope.selected = _.without($scope.selected, id)
                } else {
                    $scope.selected.push(id);
                }
                return false;
            };
            $scope.isChecked = function(id) {
                if(_.contains($scope.selected, id)) {
                    return "fa fa-check pull-right-selected";
                }
                return "";
            };
        }
    }
});

filter-button.html

<div class="row filter-item">
<div class="btn-group" dropdown is-open="{open: open}">
    <button type="button" class="btn btn-primary dropdown-toggle" dropdown-toggle ng-disabled="disabled">Fiter By {{field}} <span class="caret"></span></button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenu">
        <li data-ng-repeat="option in list" class="dropdown-btn"> <a data-ng-click="setSelectedOption()">{{option.name}}<span data-ng-class="isChecked(option.id)"></span></a></li>
    </ul>
</div>

filter.html

<filter-button list="statusList" selected="selectedStatus" field="Status" popover="Error Customer? or No Error Customer?" popover-trigger="mouseenter"></filter-button>
<filter-button list="systemList" selected="selectedSystemType" field="System Type" popover="N+1 or Stand alone?" popover-trigger="mouseenter"></filter-button>
<filter-button list="customerFilterList" selected="selectedCustomer" field="Customer" popover="Male or Female?" popover-trigger="mouseenter"></filter-button>
<div class="row filter-item">
    <div class="filter-label">
        <button class="btn btn-primary">Reset</button>
    </div>
</div>

Upvotes: 2

Views: 559

Answers (1)

Cyril Gandon
Cyril Gandon

Reputation: 17058

You can reinitialize the selected arrays on the reset click button:

<button class="btn btn-primary" ng-click="reset()">Reset</button>

In you controller:

$scope.reset = function() {
    $scope.selectedStatus = [];
    $scope.selectedSystemType = [];
    $scope.selectedCustomer = [];
}

Upvotes: 2

Related Questions