0

I am creating a select box directive where, as part of it, I need to specify if the select is multiple or not.

I have tried to set a multiple property in one of my scope objects a value of "multiple" assuming that it shall execute and set multiple="multiple" on my selectbox as follows:

<select multiple="{{properties.multiple}}" /*...(other working properties)...*/ ></select>

But this got me an error..

Error: [$compile:selmulti] http://errors.angularjs.org/1.4.4/$compile/selmulti?p0=%3Cselect%20id%3D%22…y%20as%20value%20for%20(key%20%2C%20value)%20in%20properties.options%22%3E
    at Error (native)
    at path/to/angular/angular-1.4.4/angular.min.js:6:416
    at X (path/to/angular/angular-1.4.4/angular.min.js:71:93)
    at ha (path/to/angular/angular-1.4.4/angular.min.js:56:379)
    at S (path/to/angular/angular-1.4.4/angular.min.js:54:425)
    at path/to/angular/angular-1.4.4/angular.min.js:68:209
    at path/to/angular/angular-1.4.4/angular.min.js:118:217
    at n.a.$get.n.$eval (path/to/angular/angular-1.4.4/angular.min.js:133:39)
    at n.a.$get.n.$digest (path/to/angular/angular-1.4.4/angular.min.js:130:60)
    at n.scopePrototype.$digest (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:1955:23)

I can use ng-if but am trying to find a better approach than making redundant select tags to differentiate between standard and multiple.

What could be a better approach?

KAD
  • 10,972
  • 4
  • 31
  • 73

2 Answers2

0

Create your own directive that use ng-ifs or write a directive with logic to switch between single and multiple. Looks like angular didn't want to do that but if it works for you, go for it.

micah
  • 7,596
  • 10
  • 49
  • 90
0

One possibility would be to add a link function to your directive definition that checks the properties.multiple value off your scope and then uses jquery or jqLite to set the attribute. So:

angular.directive("yourDirective", function() {    return {
      link: function(scope, element, attrs) {
           if (scope.properties.multiple) {
              elements.children("select").attr("multiple",true);
           }
      },
      templateUrl: "yourtemplate.html", ...    
      } 
});
John Christensen
  • 5,020
  • 1
  • 28
  • 26
  • As this makes the selectbox a multi-select, it does not behave properly though. Meaning if you set the ng-model value to `["2"]` of the selectbox, option with `value="2"` will not be selected (knowing that it exists). Besides, this created an empty option in the multi-select with `value="?"`. I also tried using controller rather than link but with not luck.. I guess i will be going for the `ng-if`. Thanks for your help.. – KAD Sep 15 '15 at 18:22