ng-selected在选择字段中不起作用

时间:2016-09-02 13:24:15

标签: angularjs

我正在尝试将选择字段的默认值设置为设置选项,但它不起作用,我似乎无法弄清楚我做错了什么?

在我的控制器中我有:

$scope.interp_id = "2"; // set the default id
$http.get("web/controllers/get.php")
.then(function (response) {
    $scope.interpreters = response.data.records;
});

get.php是一个返回json的php文件(这个工作正常)。

我的选择如下:

<select ng-model="interpreters_id">
    <option ng-repeat="x in interpreters" value="{{x.id}}" ng-selected="{{x.id == interp_id}}">{{x.first_name}} {{x.middle_name}} {{x.last_name}}</option>
</select>

当我在浏览器中查看它时,它看起来像: enter image description here enter image description here

但是当我检查元素时,它显示选项ng-selected为True。

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:2)

ngOptions是在Angular中使用select元素的推荐方法。

另外,如果你查看ngSelected文档,有一个黄色框表示它与select和ngModel属性无法正常工作,这在某种程度上是你想要做的。< / p>

ngRepeat很乐意重复您的选项元素,但这不是使用select元素的正确方法。

我有prepared a fiddle让你尝试一下。

<div ng-app="ngOptionsApp">
    <div ng-controller="ExampleController">
        <select ng-model="selectedInterpreter" ng-options="interpreter as interpreter.name for interpreter in interpreters track by interpreter.id">
            <option value="">Select an Interpreter</option>
        </select>  

        {{selectedInterpreter}}
    </div>
</div>

angular.module('ngOptionsApp', []).controller('ExampleController', ['$scope', function($scope) {
    $scope.interpreters=[{id: 1, name:'Gill Bates'}, {id: 2, name:'Cohn Jarmack'}, {id: 3, name:'Melon Musk'}];
    $scope.selectedInterpreter = $scope.interpreters[0];
}]);

希望它有所帮助;)

答案 1 :(得分:0)

您不应在ng-selected指令中使用花括号。你可以尝试一下吗?

<option ng-repeat="x in interpreters" value="{{x.id}}" ng-selected="x.id == interp_id">{{x.first_name}} {{x.middle_name}} {{x.last_name}}</option>

http://jsfiddle.net/endrcn/44j19ngp/

相关问题