Using checkboxes and required with AngularJS

后端 未结 5 1598
独厮守ぢ
独厮守ぢ 2021-01-31 08:20

I\'ve tried to use the html5 required attribute for my group of checkboxes but I don\'t find a nice way to implement it with ng-form.

When a checkbox is che

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 09:07

    A few things:

    • I would go with an approach that just updated the entire array in this case, as it would simplify the code a little. (You might not want to do this if you're doing anything stateful with the $scope.value array contents, but it doesn't look like you are).
    • you can just use
      rather than .
    • move the submit function off of the button's ng-click and into the form's ng-submit. This makes validation management a little easier with angular's built-in validation (if you care about that)
    • If your wraps your you don't need the for="" attribute.

    Here is an updated fiddle for you

    And here's the code:

    {{value}}

    JS

    function myCtrl($scope) {
    
        $scope.choices = [{
            "id": 1,
            "value": "1",
            "label": "Good"},
        {
            "id": 2,
            "value": "2",
            "label": "Ok"},
        {
            "id": 3,
            "value": "3",
            "label": "Bad"}];
    
        $scope.value = [];
    
        $scope.updateQuestionValues = function() {
            $scope.value = _.filter($scope.choices, function(c) {
                return c.checked;
            });
        };
    }​
    

提交回复
热议问题