簡體   English   中英

AngularJS綁定復選框以建模屬性

[英]AngularJS binding checkboxes to model property

我有一個AngularJS應用程序,其中包含一個用戶列表,每個用戶旁邊都有一個“編輯”按鈕。 每個用戶都有許多與之相關的主題。 當我點擊“編輯”時,它會打開一個表單,您可以在其中編輯用戶詳細信息,並從復選框列表中選擇相關主題。 我正在試圖弄清楚如何綁定主題復選框,以便檢查用戶已經關聯的主題,其余部分未選中。 任何建議贊賞。

我的HTML:

<form name="UserEditForm">
 Name: <br /> <input type="text" name="name" ng-model="user.name"> <br />
{{name}}

Email: <br /> <input type="text" name="name" ng-model="user.email"> <br />
{{email}}

 <div class="control-group">
            <label class="control-label" for="inputSubjects">Subjects:</label>
            <div class="form-group">
              <label ng-repeat="subject in subjects" class="checkbox">
              <input type="checkbox" ng-checked="{user.subjects}"  name="selectedSubjects[]" value="{{subject.id}}" ng-model="subject.selected"> {{subject.name}}
              </label>
        </div>

<br />

<a ng-click="updateUser()" class="btn btn-small btn-primary">Save Changes</a>

</form>

我的UserEditCtrl:

angular.module('myApp.controllers')
    .controller('UserEditCtrl', ['$scope', '$routeParams','SubjectsFactory', 'UserFactory', '$location',
    function ($scope, $routeParams, SubjectsFactory, UserFactory, $location) {

        // callback for ng-click 'updateUser':
        $scope.updateUser = function () {
            $scope.user.subjects = $scope.selection;
            UserFactory.update($scope.user);
            $location.path('/users');
        };

        // callback for ng-click 'cancel':
        $scope.cancel = function () {
            $location.path('/users');
        };

        $scope.user = UserFactory.show({id: $routeParams.userid});
        $scope.subjects = SubjectsFactory.query();

        $scope.selection = [];

    // helper method
    $scope.selectedSubjects = function selectedSubjects() {
      return filterFilter($scope.subjects, { selected: true });
    };

    // watch subjects for changes
    $scope.$watch('subjects|filter:{selected:true}', function (nv) {
      $scope.selection = nv.map(function (subject) {
        return subject.id;
      });
    }, true);


    }]);

正如@jkinkead所說,你的代碼看起來不錯,我根據你的ng-model表達式修復了ng-checked綁定

這是一個簡化的plunker: http ://plnkr.co/edit/qaIBExtVbNdSXlQlbMym?p = preview

編輯1:我編輯並改進了plunker以更接近您的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM