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.

3

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.