AngularJS - Selects and ng-options
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<script src="https://code.angularjs.org/1.2.16/angular.js"></script>
<div ng-app="myapp">
<div ng-controller="FirstCtrl">
<select my-options-months ng-model="selectedMonth"></select>
<br>{{ selectedMonth }}</div>
</div>
JavaScript
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.selectedMonth = 3
})
.directive('myOptionsMonths', function ($compile) {
return {
priority: 1001, // compiles first
terminal: true, // prevent lower priority directives to compile after it
compile: function (element, attrs) {
element.attr("ng-options", "m for m in months");
element.removeAttr('my-options-months'); // necessary to avoid infinite compile loop
var fn = $compile(element);
return function (scope) {
scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
fn(scope);
};
}
}
})