繁体   English   中英

如何从angularjs指令中的ng-options返回对象的索引

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

我试图使用指令使月选择器。 我将月份定义为索引/名称对象的数组,并使用ng-options在指令中创建一个select下拉列表。

我的目标是

  • 作为本地范围变量传入月份,
  • 更新变量,并
  • 以可读的html形式(例如:)

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

到目前为止,我将月份作为整数传递,但是一旦进行选择,它就会作为一个对象出现。 例如

IN 1 :用户选择Jun:

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

我只希望模型值变为6。

这是我的指令:

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>'
    };
});

有没有一种方法可以更改它,使其仅更新月份索引?

这是一个插件: http ://plnkr.co/edit/LVqRUCVO6Rpr9QlDtacQ?p=preview

将模板更改为

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

也许,如果您愿意,可以将指令的控制器重构为

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM