AngularJS复选框值

时间:2016-06-17 05:37:22

标签: angularjs checkbox

我需要为我的复选框分配一个值。当选中该框时,它会给我一个未定义的值。请告诉我代码中的错误:

$scope.days = [
            {
                day: '0',
                name: 'Sunday'
            },
            {
                day: '1',
                name: 'Monday'
            },
            {
                day: '2',
                name: 'Tuesday'
            },
            {
                day: '3',
                name: 'Wednesday'
            },
            {
                day: '4',
                name: 'Thursday'
            },
            {
                day: '5',
                name: 'Friday'
            },
            {
                day: '6',
                name: 'Saturday'

HTML

抱歉,由于格式化不起作用,我必须包含html代码的屏幕截图。

我需要复选框值等于days.day。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要创建,您需要先创建角度控制器和服务

`angular.module('checkboxApp', [])

.factory('checkBoxFactory', function() {
  var checkboxes = function(jsonObject) {
    for (var category in jsonObject) {
      for (var i = 0; i < jsonObject[category].length; i++) {
        jsonObject[category][i].check = false;
      }
    }
    return jsonObject;
  }

  return {
    create: function(jsonObj) {
      return new checkboxes(jsonObj);
    }
  }
})

.directive('checkboxes', function() {

  return {
    restrict: 'E',
    scope: {
      data: '=data'
    },
    template: '<div><div ng-repeat="(category, tags) in data"><h3>{{category}}</h3><span ng-repeat="tag in tags"><input type="checkbox" ng-model="tag.check"> {{ tag.name }} <br/></span></div> </div>',
    controller: function($scope) {

    }
  }
})


function TestCtrl($scope, checkBoxFactory) {
  var jsonObject = {
    "Days": [{
      day: '0',
      name: 'Sunday'
    }],
    "Service": [{
      day: '0',
      name: 'Sunday'
    }, {
      day: '1',
      name: 'Monday'
    }, {
      day: '2',
      name: 'Tuesday'
    }, {
      day: '3',
      name: 'Wednesday'
    }, {
      day: '4',
      name: 'Thursday'
    }, {
      day: '5',
      name: 'Friday'
    }]
  };

  $scope.checkboxes1 = checkBoxFactory.create(jsonObject);
}

之后,通过添加以下HTML代码

为您的复选框添加HTML
  <div ng-app="checkboxApp" ng-controller="TestCtrl">
  <checkboxes data='checkboxes1'></checkboxes>
  <p>Name: {{checkboxes1.Name[0].check}}
    <p>
      <p>Service good: {{checkboxes1.Service[0].check}}
        <p>
          <p>Service bad: {{checkboxes1.Service[1].check}}
            <p>
</div>

Click here用于演示