AngularJS / HAML : Add CSS class if property is true

339 Views Asked by At

I work in customizing element of an ItemSelector directive, data of ItemSelector coming from rails server.

here is the haml code :

.directive-items-selector{ ng_click: "openItemsSelector( $event )" }
  .wrapper
    %ui_select.ui-select{ ng: { model:  "input.model", disabled: "disabled",
                                change: "itemSelectModelChanged()" },
                        search_enabled: "{{ options.searchable }}" }

      %ui_select_match.ui-select-match{ items_selector_match: '',
                                        placeholder: "{{ input.placeholder }}",
                                        allow_clear: "{{ options.clearable }}",
                                        title:       "{{ $select.selected.label }}"                                        }
        %i.fa{ ng_class: 'icon' }

        {{ $select.selected.label }}

        %i.archived.fa.fa-archive{ ng_if: '$select.selected.object.is_archived' }

          %span.archived{ translate: 'archived.yes' }
      %ui_select_choices.ui-select-choices{ repeat:  "item.id as item in input.filteredItems track by item.id",
                                            refresh: "reloadItems( $select.search )",
                                            refresh_delay: '{{ input.filterDelay }}' }
        .item{ ng_attr_title: "{{ ::item.label }}" }
          .item-label {{ ::item.label }}
          %small.item-details {{ ::item.details }}

    .items-selector-actions
      %a.pointer.action{ ng: { if: 'linkToModal', click: 'openDetails()', disabled: "!model"  }}
        {{ 'btn.details' | translate }}
        %a.pointer.action{ ng: { if: 'createButton && klassName && !disabled', click: 'createItem()' }}
          {{ 'btn.new' | translate }}

I test if the object selected is archived or not by :

$select.selected.object.is_archived

for now I'm adding an icon and a small text to tell user that this object selected is archived, what what I want is to change that and add text-decoration: line-through red; to be like that : enter image description here

how to add css class depend on $select.selected.object.is_archived value

1

There are 1 best solutions below

4
On

Ng-class accepts object, where key is your class and value is condition, when it is to be applied:

ng-class="{'desiredClass': $select.selected.object.is_archived}"

Or another solution is using ternary operator:

ng-class="$select.selected.object.is_archived ? 'desiredClass' : ''"


In HAML, via various usages:

%div{'ng-class': "{'desiredClass': condition === true}"}
%div{'ng_class': "{'desiredClass': condition === true}"}
%div{'ng': {'class': "{'desiredClass': condition === true}"}}

Here working codepen example: https://codepen.io/anon/pen/pKreGv?editors=1010