Angularjs:在下拉列表中在运行时定义列

时间:2014-10-21 16:15:43

标签: javascript angularjs

我有一个与json对象绑定的下拉列表。

我想在运行时定义下拉列表的列名。请帮忙

代码段:

<!DOCTYPE html>

    

<div ng-controller="HelloController">

    <select ng-options="p.name for p in phones" ng-model="p.name"></select>

</div>


<script>
    angular.module("myapp", [])
    .controller("HelloController", function ($scope) {
        $scope.helloTo = {};
        $scope.selectedVal = "name";
        $scope.helloTo.title = "World, AngularJS";
        $scope.phones = [{
            'name': 'Nexus S',
            'snippet': 'Fast just got faster with Nexus S.',
            'age': 1
        }, {
            'name': 'Motorola XOOM™ with Wi-Fi',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 2
        }, {
            'name': 'MOTOROLA XOOM™',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 3
        }];

    });

</script>

我想定义类似 $ scope.selectedVal

的内容
 <select ng-options="$scope.selectedVal for p in phones" ng-model="p.name"></select>

2 个答案:

答案 0 :(得分:0)

试试这个

     <select ng-options="p[selectedVal] for p in phones" ng-model="selectedOption"></select> 

答案 1 :(得分:0)

您可以使用以下代码执行此操作。

<div ng-controller="MyCtrl">
     <select ng-options="p.name for p in phones" ng-model="selectedValue"></select>
</div>

function MyCtrl($scope) {
    $scope.phones = [
        {
            'name': 'Nexus S',
            'snippet': 'Fast just got faster with Nexus S.',
            'age': 1
        }, 
        {
            'name': 'Motorola XOOM™ with Wi-Fi',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 2
        }, 
        {
            'name': 'MOTOROLA XOOM™',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 3
        }
    ];
    $scope.selectedValue = $scope.phones[0];
}

这是JSFiddle您的示例。