AngularJs ng-repeat中使用ng-model

在ng-repeat中使用ng-model的時候發現數據並無綁定成功,緣由是ng-repeat之間的代碼,對全局的$scope裏變量的內容是不可見的,也就是說ng-repeat之間的代碼和變量是在子$scope中的,因此若是想要引用全局$scope裏的成員,能夠使用$parent 來引用全局的$scope。html

引用:http://zhaoyanblog.com/archives/97.htmlapp

這裏舉兩個比較典型的例子:spa

  • 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}code

  • 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}htm

相關文章
相關標籤/搜索