以下是代码:
HTML
<form ng-submit="fun()">
<select ng-model="a" ng-options="table.id as table.name for table in tables></select>
<input type="text" ng-model="b">hello</input>
<input type="submit">Ok</input>
</form>
JS
$scope.tables = [{"id":1, "name":"x"},{"id":2, "name":"y"},{"id":3, "name":"z"}];
//This is dummy data, tables is actually coming from another custom API
$scope.fun = function(){
console.log($scope.a);
console.log($scope.b);
}
这是输出:
undefined
hello
当我检查源代码时,附加到我的选择的选项看起来像这样:
<option label="x" value="undefined:undefined"></option>
如何在ng-submit中获取控制器中的选定选项?
答案 0 :(得分:1)
检查此....当您更改了我用
更新的数据时
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.tables = [{"id":1, "name":"x"},{"id":2, "name":"y"},{"id":3, "name":"z"}];
$scope.fun = function(){
console.log($scope.a);
console.log($scope.b);
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<form ng-submit="fun()">
<select ng-model="a" ng-options="table.id as table.name for table in tables"></select>
<input type="text" ng-model="b">
<input type="submit">
</form>
</body>
</html>
答案 1 :(得分:0)
因为您要访问table.id
中的table.name
和ng-options
,您需要将数组更改为此对象数组
$scope.tables = [{"id":"1","name":"1"},{"id":"2","name":"2"},{"id":"3","name":"3"}];
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.tables = [{"id":"1","name":"1"},{"id":"2","name":"2"},{"id":"3","name":"3"}];
$scope.fun = function(){
console.log($scope.a);
console.log($scope.b);
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form ng-submit="fun()">
<select ng-model="a" ng-options="table.id as table.name for table in tables"></select>
<input type="text" ng-model="b" />
<input type="submit"/>Ok
</form>
</div>
&#13;
如果您不想更改数组,只需将ng-options
更改为此
ng-options="table as table for table in tables"
演示
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.tables = ["1","2","3"];
$scope.fun = function(){
console.log($scope.a);
console.log($scope.b);
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form ng-submit="fun()">
<select ng-model="a" ng-options="table as table for table in tables"></select>
<input type="text" ng-model="b" />
<input type="submit"/>Ok
</form>
</div>
&#13;