如何使用ng-model绑定值

时间:2017-03-30 07:36:10

标签: javascript angularjs cordova ionic-framework

我正在开发一个应用程序,我正面临这个类似的问题。我基于API响应动态创建选择框。我不明白如何在控制器中绑定这些值。参考代码是



var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // how to get values of input boxes here
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model= "What_Should_Go_Here" ng-repeat="x in [10,11,22,33]">
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
</select>
{{What_Should_Go_Here}}
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

初始化空对象selected = {}

然后,使用ng-repeat循环选择框,在每个选择框中,使用ng-options获取选择的选项。

现在,对于每个选择中的每个选定值,ng-model="selected[y]"会使用select标记键将当前选择值推送到选定对象

因此,在选择所有选择后,所选对象看起来很糟糕,

<强> {"1":11,"2":10,"3":22,"4":22}

请运行以下代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selected[y]" ng-options="x for x in data" ng-repeat="y in selects" ng-change="selectedFunc(y)">
</select>
<br><br>
Selected Values: {{selected}}
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selected = {};
$scope.selects = [1,2,3,4]
$scope.data = [10,11,22,33]


$scope.selectedFunc = function(y)
{
 alert($scope.selected[y])
}

    
});
</script>


</body>
</html>

Here is a working DEMO

答案 1 :(得分:0)

使用带有ng-change方法的选择框,并将模型值传递给下面的更改函数.....以便您可以访问js中的所选项目

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.array=[10,11,22,33];//assuem it as your db result 
  $scope.fix=function(val){
    console.log(val);
  }
});
<!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">
  <select ng-model= "x" ng-options="x as x for x in array" ng-change="fix(x)"</select>
  {{x}}
  </body>

</html>