问题
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?
回答1:
Create your own directive that use ng-if
s 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.
回答2:
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", ...
}
});
来源:https://stackoverflow.com/questions/32573299/conditional-multi-select-directive-in-angular