简体   繁体   中英

ng-options duplicating option in select

I select element bound with a list using ng-options. I have a custom directive which adds validation directive to the select element. This custom directive compiles the select element. After compiling the select element, the options are duplicated. Is there a way to stop the duplication or clear them before compiling atleast ?

In the below code, metadata is a custom directive. In that directive, I have the compile($el)($scope) line. After executing this line, select becomes like below

Please select gender
Male
Female
Male
Female

 function ($scope, $el, $attr, $ngModel) { if (!$ngModel) { return; } var elementMetadata = JSON.parse($attr.metadata); angular.forEach(elementMetadata.validators, function (item) { $el.attr(item.name, item.value); }); $el.removeAttr('metadata'); $compile($el)($scope); } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <select name="gender" id="lstGender" ng-options="gender for gender in genderList track by gender" ng-model="fields.gender" metadata="{{template.gender}}"> <option value="">Please select gender</option> </select> 

Move the compiling select element to last function of compiling to execute by using post

          pre: function(scope, element) {
            scope.values =  [ 'male', 'female' ];
          },
          post: function() {
            $compile(tElement)(scope);
          }

codepen- https://codepen.io/nagasai/pen/MQQLbB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM