Wednesday, April 13, 2022

How remove first empty element in dropdown in AngularJS1.4.3

Hello, currently I have some count of legacy projects on the support, and they are has been created with AngularJS 1.4.3.


This is framework has features what first element in dropdown will be empty.

By design, it must be an element with label as 'Select from dropdown'.

Problem:



The original code:

<select ng-model="feed.config">
    <option ng-repeat="template in configs" ng-selected="$first">{{template.name}}</option>
</select> 


Because this is versions is intermediate, solutions as

<option value="" style="display: none"></option>

or

<option value="" ng-if = "false"></option>

or

this solution will be works correctly:
<select ng-model="model.id" convert-to-number>
  <option value="0">Zero</option>
  <option value="1">One</option>
  <option value="2">Two</option>
</select>
{{ model }}

angular.module('nonStringSelect', [])
.run(function($rootScope) {
  $rootScope.model = { id: 2 };
})
.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return parseInt(val, 10);
      });
      ngModel.$formatters.push(function(val) {
        return '' + val;
      });
    }
  };
});
And result:

No comments:

Post a Comment