在ng-repeat中使用ng-model的时候发现数据并没有绑定成功,原因是ng-repeat之间的代码,对全局的$scope里变量的内容是不可见的,也就是说ng-repeat之间的代码和变量是在子$scope中的,所以如果想要引用全局$scope里的成员,可以使用$parent 来引用全局的$scope。
引用:http://zhaoyanblog.com/archives/97.html
这里举两个比较典型的例子:
- 1. 在RadioButton中使用ng-repeat和ng-model,绑定的是同一个变量。假设需求是这样的:有3个不同颜色的单选按钮,选择一个颜色之后点击保存按钮向后台发送一个这种格式的数据:{colorId: 0}
<body ng-controller="ctrl"> <div ng-repeat="color in colorList"> <input type="radio" value="{{ color.id }}" name="radio" ng-model="$parent.colorId"> <label>{{ color.name }}</label> </div> <input type="button" ng-click="save(colorId)" value=" SAVE "> <script> var app = angular.module('myApp', []); app.controller('ctrl', function ($scope) { $scope.colorList = [{name: "orange", id: 1}, {name: "red", id: 2}, {name: "blue", id: 3}]; $scope.save = function (colorId) { var data = {"colorId": parseInt(colorId)}; console.log(data); } }); </script> </body>
控制台输出结果: {colorId: 3}
- 2. 在Checkbox中使用ng-repeat和ng-model,每个复选框分别绑定一个变量。并且假设页面上显示的复选框的名字和向后台发送的变量名字不一样。
<body ng-controller="ctrl"> <div ng-repeat="day in dayList"> <input type="checkbox" name="radio" ng-model="$parent.appointment[day.modelName]"> <label>{{ day.displayName }}</label> </div> <input type="button" ng-click="save()" value=" SAVE "> <script> var app = angular.module('myApp', []); app.controller('ctrl', function ($scope) { $scope.appointment = { "Sun": false, "Mon": false, "Tue": false, "Wed": false, "Thu": false, "Fri": false, "Sat": false }; $scope.dayList = [{ modelName : "Sun", displayName: "U" }, { modelName : "Mon", displayName: "M" }, { modelName : "Tue", displayName: "T" }, { modelName : "Wed", displayName: "W" }, { modelName : "Thu", displayName: "R" }, { modelName : "Fri", displayName: "F" }, { modelName : "Sat", displayName: "S" }]; $scope.save = function () { console.log($scope.appointment); } }); </script> </body>
控制台输出结果: {Sun: true, Mon: true, Tue: true, Wed: false, Thu: false, Tue: true, Wed: false}