ng-options in directive
to test diff version situation
by butylinda
HTML
<script src="https://code.angularjs.org/1.4.0/angular.min.js"></script>
<h1>1.4.0</h1>
<div ng-controller="FirstCtrl">Initialized to 3:
<select ng-model="selectedMonth" my-options-months=""></select>
<hr />Uninitialized (defaults to 1):
<select ng-model="selectedMonth2" my-options-months=""></select>
</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('FirstCtrl', function ($scope) {
$scope.selectedMonth = 3;
});
app.directive('myOptionsMonths', ['$timeout', '$compile', function ($timeout, $compile) {
return {
priority: 1,
require: 'ngModel',
compile: function (tElem, tAttrs) {
tAttrs.$set('ngOptions', 'month for month in months');
tAttrs.$set('myOptionsMonths', null);
tElem.removeAttr('myOptionsMonths'); // add because $compile
var fn = $compile(tElem); // add because $compile
return function (scope, elem, attrs, ctrl) {
scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$timeout(function () {
if (ctrl.$viewValue === undefined) {
ctrl.$setViewValue(scope.months[0]);
}
fn(scope); // add because $compile
});
};
}
};
}]);