Renato Oliveira Renato Oliveira - 7 months ago 59
Javascript Question

Picklist with Angular JS parsing list

I have a list of strings with years on it, like:

$scope.years = ["2001", "2002", "2003", ...];


I'm trying to render it on a page inside a
select
tag, but angular keeps breaking the code, rendering the elements outside the tag.

I have the following in the page:

<select>
<option value="" disabled selected>----</option>
<option ng-repeat="y in years" value="{!y!}">{!y!}</option>
</select>


I does render, but all the option tags that are generated, are outside the select tag. Am I doing something wrong here?

Edit: using AngularJS 1.5.3

Answer

You can use ng-options, which is the recommended way in AngularJS, and has a lot of performance improvements over ng-repeat for this case.

It will require you to have ng-model as well. And you can still have your custom "Empty/Select" option.

It will look like this:

<select ng-model="something" name="S" 
        ng-options="y for y in years">
  <option value="" disabled selected>----</option>
</select>

A full working example:

var app = angular.module("TestApp", []).controller("sample", ["$scope",
  function($scope) {
    $scope.years = ["2001", "2002", "2003"];
  }
]);

angular.bootstrap(document, ["TestApp"]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>

<div ng-controller="sample">
  <select ng-model="something" name="S" ng-options="y for y in years">
    <option value="" disabled selected>----</option>
  </select>
</div>

P.S.

I'm assuming the ! in your code is by mistake, if not, you cannot do this transformation in HTML. You better have another array with the formatted results, and watch the original array to update the transformation one.

Comments