2

I need to set multiple attribute for select tag dynamically.

According to this documentation: https://www.thinkingmedia.ca/2015/03/conditionally-add-a-html-element-attribute-value-in-angularjs/#using-the-ngattr

This should work:

<select ng-attr-multiple="param.MultiValue">

and become

<select multiple>

if param.MultiValue evaluates to true, otherwise - without multiple attribute.

Doesn't work, I get select tag without multiple attribute regardless.

Even if I use

<select ng-attr-multiple="true">

Any idea why?

Thanks.

monstro
  • 6,254
  • 10
  • 65
  • 111
  • Related: http://stackoverflow.com/questions/31872232/conditionally-add-the-multiple-attribute-to-ui-select – Michael Yaworski Jan 23 '17 at 17:45
  • There are hundreds Google results related, none is explaining why this is not working :) – monstro Jan 23 '17 at 17:52
  • You can't use angular interpolation on boolean attributes. See here: https://docs.angularjs.org/guide/interpolation I'd suggest using the link that @mikeyaworski posted or this one: http://stackoverflow.com/questions/24043732/conditional-multiple-attribute-in-input-type-file-with-angularjs – JGibbers Jan 23 '17 at 18:07
  • I didn't get you @JGibbers. Where is the interpolation being used? Did i miss something? – Nikhilesh Shivarathri Jan 23 '17 at 18:11

1 Answers1

3

Web browsers are sometimes picky about what values they consider valid for attributes. ng-attr is for binding arbitrary attributes, select does not "know" that ng-attr-multiple is trying to set the multiple attribute, it just reacts on multiple directly.

Instead I would suggest you to write a wrapper directive which will add the multiple attribute to your element.

For more information on this see this documentation link:

https://docs.angularjs.org/guide/interpolation

Issue link:

https://github.com/angular/angular.js/issues/13570

var mymodule = angular.module('myApp', []);

function sampleController($scope, $timeout) {
  $scope.addAttribute = true;
}

mymodule.controller('sampleController', sampleController)

.directive('multipleAttr', function() {
  return {
    'restrict': 'A',
    'compile': function() {
      return {
        'pre': function($s, $el, attrs) {
          if (attrs.multipleAttr === 'true' || attrs.multipleAttr === true) {
            $el.attr('multiple', true);
          }
        }
      }
    }
  }

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="sampleController">
    <select multiple-attr="{{addAttribute}}">
      <option>Hi</option>
      <option>Hello</option>
      <option>Hey</option>
    </select>
  </div>
</div>
Nikhilesh Shivarathri
  • 1,640
  • 10
  • 16