Search code examples
javascriptangularjsui-selectangular-ui-selectangularjs-ng-if

Angular 1/ ng-if one-time binding only in a condition


In my template i have :

<div ng-if="$ctrl.show()">
  <input class="form-control" type="text">
</div>

In my component

  show() {
    if (angular.isDefined(this.parking.parkingType)) {
      return this.parking.parkingType.labelKey === 'parking_type.air'
    }
  }

I want angular to process the function only when clicking on a select input (ui-select) by the attribute on-select="$ctrl.show()" :

 <ui-select ng-model="$ctrl.parking.parkingType"
             on-select="$ctrl.show()">
    <ui-select-match allow-clear="true">
        <span>{{ $select.selected.label }}</span>
    </ui-select-match>
    <ui-select-choices repeat="item in $ctrl.parkingType | filter: { label: $select.search }">
        <span ng-bind-html="item.label"></span>
    </ui-select-choices>
  </ui-select>

This case may be similar to a sample case of: launching the function only when clicking on an ng-click


Solution

  • change your ng-show to a variable and keep on-select="$ctrl.show()" as is

    In your view:

    <div ng-if="$ctrl.shouldShow">
      <input class="form-control" type="text">
    </div>
    

    In your component:

    $ctrl.show = function() {
      if (angular.isDefined(this.parking.parkingType)) {
        $ctrl.shouldShow = (this.parking.parkingType.labelKey === 'parking_type.air')
      }
    }
    

    It's a good practice not to have a function in ng-if, ng-show, and ng-hide because it's a performance hit