选择全部或一个复选框以启用提交按钮angularjs

时间:2019-01-30 20:17:08

标签: javascript angularjs

我是angularjs的新手。我正在尝试一个具有复选框和禁用按钮的简单程序。选择一个或多个复选框后,应启用该按钮。但是,我的解决方案似乎无法正常工作。在这方面的任何帮助将是巨大的。 HTML代码:

   <html ng-app="Apps" ng-controller = "chk">
<head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="Apps.js"></script>
</head>
<body>
<center>
<h1> Fruits </h1>
<hr/>
<div >

<label ng-repeat="lbl in lbls">
  <input type="checkbox" ng-model="chkd" > {{lbl}}
</label>
<br>
<input type="button" value="Submit" ng-disabled="!chkd"/>
</div>
</center>
</body>
</html>

这是JS文件:

    var Apps = angular.module ('Apps', [])
Apps.controller("chk", function($scope){

$scope.lbls = [
    'Apples', 
    'Bananas', 
    'Apricots', 
    'Peaches'
  ];

});

2 个答案:

答案 0 :(得分:1)

对于ng-disabled,要想检测到更改,每个复选框都必须具有单独的条件。请改用以下HTML布局:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/envelope">
    <xsl:element name="{payload/@class}Envelope">
        <xsl:copy-of select="action"/>
        <logId>
            <xsl:value-of select="auditId"/>
        </logId>
        <xsl:copy-of select="payload"/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

jsfiddle

编辑 代码现在应该可以正常工作了。抱歉造成混乱!

答案 1 :(得分:0)

这是一种您可以插入其他水果,而无需在ng-disabled中更改代码的方法:

 var Apps = angular.module ('Apps', [])
Apps.controller("chk", function($scope){
$scope.chkd = {
                Apples: false, 
                Bananas: false,
                Apricots: false,
                Peaches: false
                };

$scope.enableSubmit = function(){
  var atLeastOneSelected = [];
  
  for (var fruit in $scope.chkd) {
      if($scope.chkd[fruit] === true){
        atLeastOneSelected.push(fruit);
      }
  }
  
  return !(atLeastOneSelected.length > 0);
}

});
<html ng-app="Apps" ng-controller = "chk">
<head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="Apps.js"></script>
</head>
<body>
<center>
<h1> Fruits </h1>
<hr/>
<div >

<label ng-repeat="(lbl, enabled) in chkd">
  <input type="checkbox" ng-model="chkd[lbl]"> {{lbl}}
</label>
<br>
<input type="button" value="Submit" ng-disabled="enableSubmit()"/>
</div>
</center>
</body>
</html>