在ng-repeat中使用ng-model的時候發現數據並無綁定成功,緣由是ng-repeat之間的代碼,對全局的$scope裏變量的內容是不可見的,也就是說ng-repeat之間的代碼和變量是在子$scope中的,因此若是想要引用全局$scope裏的成員,能夠使用$parent 來引用全局的$scope。html
引用:http://zhaoyanblog.com/archives/97.htmlapp
這裏舉兩個比較典型的例子:spa
<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}code
<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}htm