bibs
bibs

Reputation: 1226

ngOptions applied twice in custom directive

I am creating a directive that replaces a normal a select tag with a customized one:

angular.module('myModule').directive('mySelect', function() {
 return {
   restrict: 'AE',
   require: 'ngModel',
   templateUrl: 'mySelect.html'
   replace: true,
   scope: true,
   controller: ['$scope', function($scope) { $scope.options = [1,2,3,4,5] }],
   link: function(scope, element, attrs, ctrl) {
      // No updates to scope here
   }
 }
});

And the template looks like:

<select ng-model="value" ng-options="(x | sprintf:'%02d') for x in options"></select>

For some strange reason, the options created by ng-options are applied twice. The resulting HTML looks like:

<select my-select ng-options="(x | sprintf:'%02d') for x in options" class="...">
  <option value="?" selected="selected"></option>
  <option value="0">01</option>
  <option value="1">02</option>
  <option value="2">03</option>
  <option value="3">04</option>
  <option value="4">05</option>
  <option value="?" selected="selected"></option>
  <option value="0">01</option>
  <option value="1">02</option>
  <option value="2">03</option>
  <option value="3">04</option>
  <option value="4">05</option>
</select>

Anybody know what's going on?

Upvotes: 1

Views: 834

Answers (1)

zs2020
zs2020

Reputation: 54524

You should use div instead of <select my-select></select> like this

<div my-select></div>

The directive mySelect return another select directive so you will get the error Error: Multiple directives [select, select] because the HTML will be rendered as

<select ng-options="x for x in options" ng-model="value" my-select=""></select>

Demo

Upvotes: 2

Related Questions