我的angular ng-options指令不起作用。更改选项时,ng模型未更新。
角片段
scope.searchoptions = [
{ name: "All", id: 1 },
{
name: "Devices",
id: 2
}, {
name: "Sessions",
id: 3
}, {
name: "Alerts",
id: 4
},{
name: "Files",
id: 5
}];
scope.currentSearch = scope.searchoptions[0]; // Intial object
// Html snipets
<div class="form-group l-h m-a-0">
<select class="form-control"
ng-options="item.name for item in searchoptions track by item.id"
ng-model="currentSearch">
</select>
</div>
在选择选项时,给定代码未更新模型
请注意:在我的具体情况下,ng-init对我失败了。问题是我使用的值在ng-init运行时尚未可用:我通过ajax调用得到了值,此时ng-init已经完成
答案 0 :(得分:0)
您需要在select.ng-init="currentSearch = searchoptions[0]"
var app = angular.module("mainApp", []);
app.controller('mainCtrl', function($scope){
$scope.searchoptions = [
{ name: "All", id: 1 },
{
name: "Devices",
id: 2
}, {
name: "Sessions",
id: 3
}, { name: "Alerts", id: 4 },
{ name: "Files", id: 5 }
];
//$scope.currentSearch = scope.searchoptions[0].name; // Intial object
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<div class="form-group l-h m-a-0">
<select ng-if="searchoptions" class="form-control" ng-init="currentSearch = searchoptions[0]" ng-options="item.name for item in searchoptions track by item.id" ng-model="currentSearch">
</select>
{{currentSearch}}
</div>
</div>
&#13;
答案 1 :(得分:0)
您的代码中存在轻微错误。请查看给定的代码并更新它。给出的代码工作正常。
角片段
$scope.searchoptions = [
{ name: 'All', id: '1' },
{ name: 'Devices', id: '2'},
{ name: 'Sessions', id: '3'},
{ name: 'Alerts', id: '4' },
{ name: 'Files', id: '5' }
];
$scope.currentSearch = $scope.searchoptions[0];