0

How to add conditionally attribute in angularjs?

For example I only want to set the multiple attribute on a <select> if my component has a binding set to true. This means if the binding is not given the multiple attribute should not exist on my <select>.

The only solution I found was with ng-if.

tiktak
  • 57
  • 10

2 Answers2

1

You can achieve this by implementing a directive (aka ng-multiple) to handle the property multiple of the select element. The following snippet implements this solution. However, you may want to control the state of your model inside this directive, once the multiple prop will produce an array of selected values, the non-multiple will produce a single object, so this may cause an issue when switching between multiple and non-multiple.

angular.module('myApp', [])
  .directive('ngMultiple', function () {
    return {
      require: ['select', '?ngModel'],
      restrict: 'A',
      scope: {
        multiple: '=ngMultiple'
      },
      link: function (scope, element, attrs, ctrls) {
        
        element.prop('multiple', scope.multiple);
        
        scope.$watch('multiple', function (multiple) {
          if(element.prop('multiple') != multiple){
            // may be would be convenient change the ngModel
            // to [] or {} depending on the scenario
            element.prop('multiple', multiple);
          }
        });
      }
    };
  })
  .controller('myController', function ($scope) {
    $scope.condition = true;
    $scope.myOptions = [];
  });

angular.element(document).ready(function () {
  angular.bootstrap(document, ['myApp']);  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-controller="myController">
  <label>
    <input type="checkbox" ng-model="condition" /> multiple?
  </label>
  <br>
  <select ng-multiple="condition" ng-model="myOptions">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
    <option>Option 5</option>
  </select>
  <br>
  <tt>myOptions: {{ myOptions }}</tt>
</div>
lenilsondc
  • 9,590
  • 2
  • 25
  • 40
0

if boolean condition is true then multiple, else not

<select ng-if="condition" ng-model="some.model" multiple></select>
<select ng-if="!condition" ng-model="some.model"></select>


<select ng-show="condition" ng-model="some.model" multiple></select>
<select ng-hide="condition" ng-model="some.model"></select>

controller,

$scope.condition = true

Sravan
  • 18,467
  • 3
  • 30
  • 54