chriskelly
chriskelly

Reputation: 7736

how to return index of object from ng-options in angularjs directive

I am trying to make a month picker using a directive. I defined the months as an array of index/name objects and use ng-options to create a select drop-down in a directive.

My goal is to

<month-select month="myMonth"></month-select>

So far I pass the month as an integer but it comes out as an object once I make a selection. e.g.

IN 1: User selects Jun:

OUT { value : 6, name : 'Jun' }

I just want the model value to become 6.

Here is my directive:

app.directive('monthSelect', function () {
    return {
        restrict : 'E',
        replace : true,
        scope : { month: '=' },
        controller : function ($scope) {
            $scope.months = [];
            $scope.month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
            $scope.month_indexes = [0,1,2,3,4,5,6,7,8,9,10,11];
            $scope.month_names.forEach(function (mn, i) {
                $scope.months.push({ value : i+1, name : mn });
            });
        },
        template : '<select ng-model="month" ng-options="m.name for m in months track by m.value"></select>'
    };
});

Is there a way to change it so that it updates only the month index?

Here is a plunkr: http://plnkr.co/edit/LVqRUCVO6Rpr9QlDtacQ?p=preview

Upvotes: 0

Views: 438

Answers (1)

Mikko Viitala
Mikko Viitala

Reputation: 8404

Change your template to

<select ng-model="month" 
        ng-options="m.value as m.name for m in months">
</select>

And maybe, if you like, you could refactor your directive's controller as

var month_names = ['Jan', 'Feb', 'Mar', ..., 'Dec'];

$scope.months = [];
angular.forEach(month_names, function(name, num) {
    this.push({ value:num, name:name }); 
}, $scope.months); 

Upvotes: 2

Related Questions