0

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>
Kumaran
  • 65
  • 9
  • your code demo doesn't describe exactly what issue you are facing. Can you provide more dteails on exactly which part you are facing issue? – CodeHunter Feb 19 '18 at 17:15
  • possible duplicate - https://stackoverflow.com/questions/23595034/removing-duplicates-from-angular-js-ng-options-ng-repeat?noredirect=1&lq=1 – Naga Sai A Feb 19 '18 at 17:17

1 Answers1

0

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

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
  • This looks like a good option. But I can't hardcode the scope.values. Above code is just an example. I have several select elements like this and the directive is a generic one. Is there a way to set the options generically? – Kumaran Feb 20 '18 at 03:49
  • @Kumaran, i just harded for example, but you can use same logic of having select elements in pre function and compile in post link function – Naga Sai A Feb 20 '18 at 07:16
  • I mean to say that is there a way, I can access the current options in select in pre. Otherwise, I have to come up with a semi-hardcoded way to get it from the controller. – Kumaran Feb 20 '18 at 14:46