【问题标题】:AngularJS drop down - auto select not workingAngularJS下拉 - 自动选择不起作用
【发布时间】:2015-07-06 17:00:22
【问题描述】:

在控制器中

$scope.persons = [{"id": 1, "name": "Diso"}, {"id": 2, "name": "Tatalop"}];

在创建页面中我有这个代码。

<select name="person" ng-options="person.id as person.name for person in persons" ng-model="job.person_id">
    <option value="">Select a Person</option>
</select>

上面的下拉列表将显示人员name,其值为人员id。如果我提交表格,那么我会正确地得到人 id。这是完美的工作。

在更新页面中 我想使用相同的代码(相同的控制器和相同的 html 文件)。此下拉菜单现在需要自动选择。假设当页面加载下拉应该自动选择第二个人。为了让它成功,我在控制器中写了$scope.job.person_id = $scope.persons[1];

现在的问题是,如果我从ng-options 中删除person.id as,那么只有自动选择功能起作用,否则它不起作用。现在,如果我删除person_id as,那么我会得到整个对象({"id": 2, "name": "Tatalop"})作为下拉的结果。但我只想要id这个人。

如何做到这一点?我错过了什么吗?谁能给我推荐一下?

【问题讨论】:

    标签: javascript angularjs ng-options


    【解决方案1】:

    请检查这个小提琴可能会有所帮助 http://jsfiddle.net/linkolen/cuvjfept/

    angular.module('myApp', []);
    
    function TestCtrl($scope) {
        $scope.persons = [{"id": 1, "name": "Diso"}, {"id": 2, "name": "Tatalop"}];
        $scope.job = $scope.persons[1].id;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="TestCtrl">
        <select name="person" ng-options="person.id as person.name for person in persons" ng-model="job">
        <option value="">Select a Person</option>
    </select>
        this is the selected id: {{job}}
     <div>

    【讨论】:

    • 谢谢。我得到了答案。
    【解决方案2】:

    看这个例子:http://jsfiddle.net/kevalbhatt18/gfbksn8L/1/

    ng-change 函数中我只得到 id。

    var myApp = angular.module('myApp', []);
    
    function MainCtrl($scope) {
        $scope.persons = [{"id": 1, "name": "Diso"}, {"id": 2, "name": "Tatalop"}];
        $scope.person_id = $scope.persons[1].id;
        $scope.getValue = function(t){
        console.log(t)
    
        }
    }
    

    【讨论】:

    • 我需要自动选择功能。当我加载页面时,默认情况下我应该在下拉列表中获得Tatalop。你在找我吗?
    猜你喜欢
    • 2015-10-28
    • 2015-07-05
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2018-03-25
    • 2019-02-03
    • 1970-01-01
    • 2013-09-30
    相关资源
    最近更新 更多