Gerard Simpson
Gerard Simpson

Reputation: 2126

Adding Checkmark on click, removing all others

I have a ng-repeat with a button that looks like this:

<div data-ng-repeat="department in departments_array">
    <div class="row">
        <div class="col-md-6 dslc-button-wrapper">
            <button class="btn btn-default btn-block">Show on Map {{ 1 | checkmark }}</button>
        </div>
    </div>
</div>

I have found this filter, which I would like to use to display a checkbox when the selected element is clicked, and remove all other checkmarks from the other ng-repeat buttons at the same time:

angular.module('Filters', []).filter('checkmark', function() {
  return function(input) {
    return input ? '\u2713' : '';
  };
});

I've tried as many ways as I know how, but I've only managed to end up with being able to add or remove the checkmark on one element at a time.

Any help would be greatly appreciated

Thanks

Upvotes: 0

Views: 289

Answers (1)

Gene
Gene

Reputation: 616

Personally I wouldn't use a filter to do this. It's not the correct way of managing state in your view. A variable on your controller is a typical and readable solution. Solution Below with Plunker:

controller.js

myApp.controller('myController', function() {
  var self = this;
  self.departments_array = ['dept A', 'dept B', 'dept C'];
  self.selected_dept = undefined;
});

index.html

  <body ng-app="my-app">
    <div ng-controller="myController as mc">
      <div data-ng-repeat="department in mc.departments_array">
          <div class="row">
              <div class="col-md-6 dslc-button-wrapper">
                  <button ng-click="mc.selected=department" class="btn btn-default btn-block">
                    Show on Map <span ng-show="mc.selected===department">&#10003;</span></button>
              </div>
          </div>
      </div>
    </div>
  </body>

Upvotes: 1

Related Questions