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

标签 javascript angularjs angularjs-directive

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

我的目标是

  • 将月份作为局部范围变量传递,
  • 更新变量,并且
  • 以可读的 html 形式保存(如下所示:)

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

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

印度 1 :用户选择 Jun:

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

有没有办法更改它,使其仅更新月份索引?

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

最佳答案

将模板更改为

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

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

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

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

关于javascript - 如何从 angularjs 指令中的 ng-options 返回对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875466/

相关文章:

javascript - 链接在 JQuery 的重复区域中不起作用

php - 屏蔽状态栏中的 URL

javascript - Angular uibModal,解析,未知提供者

javascript - 图像源未与指令内的范围变量绑定(bind)

javascript - TypeError : <. ..> 不是一个函数

javascript - 修改 .htaccess 文件后,网站的某些部分无法工作

javascript - AngularJs 作用域 - 如何正确从 DOM 获取作用域?

javascript - 我应该如何构建 AngularJS 路由来处理 URL 重写和页面刷新?

javascript - 如何在没有Google SDK的情况下使用key脚本在angularjs中使用谷歌地图

javascript - 从 Angular Directive(指令)将多个参数传递给 Controller ​​函数