Skip to content

209 Delete Hero

zarlex edited this page Mar 6, 2017 · 1 revision

Delete Hero

To delete a hero we add a delete button on our list view

List view controller

Open the file hero/controllers/index.controller.js. Add a the function deleteSelected.

this.deleteSelected = function(){
  this.heroes.selectable.getSelected().secureEach(function(model){
    model.destroy();
  });
};

selectable.getSelected() always returns a collection with items that have been selected. When no item has been selected it returns an empty collection.

The secureEach() function iterates over all items of the collection that have been selected and will call destroy on them. destroy() is a function provided by BackboneJS which triggers a DELETE request.

Use the function secureEach when you iterate over a collection and delete items. When you use the .each() or .forEach() method you will have issues when trying to delete multiple items more information

List view template

Open the file hero/templates/index.template.html In the sidebar we will add our delete button.

...
<div mw-sidebar>
  <a href="...">...</a>

  <div mw-button-help>
    <button class="btn btn-danger btn-block"
            ng-click="ctrl.deleteSelected()"
            ng-disabled="ctrl.heroes.selectable.getSelected().length<1">
      <span mw-icon="fa-trash-o"></span>
      {{'hero.index.deleteHero' | i18n}}
     </button>
     <div mw-button-help-condition="ctrl.heroes.selectable.getSelected().length < 1"
          mw-button-help-text="{{'hero.tooltips.buttonHelp.nothingSelected' | i18n }}"></div>
  </div>
  ...
</div>
...

mw-button-help

This directive is useful for buttons that are disabled under some circumstances. It will add a tooltip to the button telling the user why the button is disabled.

For each disabled condition you should add a mw-button-help-condition. When the condition applies the mw-button-help-text will be displayed in the tooltip.

Button

We disable the button when the user has no items selected in the list

Provide translations

We have to add some translations for our delete button so open the file hero/i18n/en_US.json and add

{
  "hero": {
    ...
    "tooltips": {
      ...
      "buttonHelp": {
        "nothingSelected": "No hero has been selected"
      }
    },
    "index": {
      ...
      "deleteHero": "Delete hero"
    }
    ...
  }
}

and for de_DE.json

{
  "hero": {
    ...
    "tooltips": {
      ...
      "buttonHelp": {
        "nothingSelected": "Es wurde keine Held ausgewählt"
      }
    },
    "index": {
      ...
      "deleteHero": "Held löschen"
    }
    ...
  }
}
Clone this wiki locally