AngularJS / HAML:如果property为true,则添加CSS类

时间:2018-06-14 08:43:01

标签: angularjs angularjs-directive haml ng-class itemselector

我在定制ItemSelector指令的元素,来自rails服务器的ItemSelector的数据。

这里是haml代码:

.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 }}

我测试所选对象是否存档:

  

$ select.selected.object.is_archived

现在我添加一个图标和一个小文本告诉用户所选的这个对象已存档,我想要的是更改它并添加 text-decoration:line-through red; 就是这样的: enter image description here

如何添加css类取决于$ select.selected.object.is_archived值

1 个答案:

答案 0 :(得分:1)

Ng-class接受object,其中key是你的类,value是条件,当它被应用时:

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

或另一种解决方案是使用三元运算符:

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


在HAML中,通过各种用法:

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

在这里工作的代码集示例: https://codepen.io/anon/pen/pKreGv?editors=1010