AngularJS如何获得布尔值

时间:2015-08-17 20:22:58

标签: javascript html arrays angularjs checkbox

我试图找出是否选择了2个颜色复选框中的一个或两个,并且根据选择的那个/对,将在表格上输出该颜色的对象。因此,如果用户检查了"紫色"复选框然后会有一堆紫色物体输出到表格。如果"紫色"和"黄色"同时检查紫色和黄色对象都将输出到屏幕上。我一直试图检查复选框是否为" true"看看它是否被选中但我的逻辑有问题。 http://codepen.io/MarkBond/pen/pJmrxV?editors=101提前致谢

HTML

<html ng-app="formApp">

<head>
    <!-- CSS -->
    <!-- load up bootstrap and add some spacing -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
   <style>
        body         { padding-top:50px; }
        form         { margin-bottom:50px; }
   </style>

   <!-- JS -->
   <!-- load up angular and our custom script -->
       <script src="http://code.angularjs.org/1.3.14/angular.js"></script>
       <script src="app.js"></script>
</head>

    <!-- apply our angular app and controller -->

<body ng-controller="FormController as formCtrl">
    <div class="col-xs-12 col-sm-10 col-sm-offset-1">

         <h2>Angular Checkboxes</h2>

         <form>
             <div class="checkbox">
                 <label>
                     <input type="checkbox" name="displayOption" ng-model="formData.displayOption.purple" ng-click="yourFunction()" />purple
                 </label>
             </div>
             <div class="checkbox">
                 <label>
                     <input type="checkbox" name="displayOption" ng-model="formData.displayOption.yellow" ng-click="yourFunction()" />yellow
                 </label>
             </div>
         </form>
         <h2>Array/Message Output Area</h2>
         <pre>
             <div ng-repeat="object in formCtrl.objects">
                  {{ object.name }}
             </div>
             {{ message }}
         </pre>
         <!-- SHOW OFF OUR FORMDATA OBJECT -->
         <h2>Boolean Test Area</h2>
         <pre>
            {{ formData }}
         </pre>
        </div>
    </body>
</html>

AngularJS

angular.module('formApp', [])
    .controller('FormController', ['$scope' ,function($scope) {

  $scope.formData = {};

  $scope.yourFuction = function(){

    var purple = $scope.purple;
    var yellow = $scope.yellow;

    if (purple === true && yellow === true) {
        this.objects = groupOne
    } else if (purple === true) {
        this.objects = groupTwo
    } else if (yellow === true) {
        this.objects = groupOne + groupTwo
    }else{
        this.message = 'Nothing Selected'
    }
  };

    var groupOne = [
      { name: 'Grape'},
      { name: 'Wine'},
      { name: 'Toy Octipus'}
    ]

    var groupTwo = [
      { name: 'Banana'},
      { name: 'Lemon'},
      { name: 'Yellow Highlighter'}
    ]
}]);

1 个答案:

答案 0 :(得分:3)

$scope.yourFuction应为$scope.yourFunction,对于您的if语句,您应该检查$scope.formData.displayOption.purple而不是$scope.purple

var purple = $scope.formData.displayOption.purple;
var yellow = $scope.formData.displayOption.yellow;

http://codepen.io/anon/pen/LVozZG?editors=101 https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D