【问题标题】:How to bind single checkbox value with AngularJS Controller如何将单个复选框值与 AngularJS 控制器绑定
【发布时间】:2016-12-15 01:52:12
【问题描述】:

我检查了问题How to bind to list of checkbox values with AngularJS。但是这个问题解释了数组列表以及在 Angular 控制器中处理它的最佳方法。

<input type='checkbox' name="filter" checked>

我们如何将值绑定到复选框,以便在未选中时将值作为模态 0,在选中时将值作为模态 1? HTML 和 Controller 应该是什么?

$scope.filter = 0;

【问题讨论】:

标签: javascript html angularjs checkbox data-binding


【解决方案1】:

试试这个:

$scope.filter = 0;//or 1

HTML:

<input type="checkbox" ng-model="filter" ng-true-value="1" ng-false-value="0">

【讨论】:

    【解决方案2】:

    这是一个基于AngularJS documentation的修改示例

    控制器

    angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
        $scope.checkboxModel = 0; //Set checkbox to unchecked
    }]);
    

    HTML

    <input type="checkbox" ng-model="checkboxModel" ng-true-value="1" ng-false-value="0">
    

    【讨论】:

    • 我的答案的好副本。
    • 对不起,我没有看到它...我正在写我的答案
    【解决方案3】:

    Angular 提供了 ng-true-value 和 ng-false-value 指令来满足您的要求。通过它,您可以将真/假值与复选框相关联,并且模型也将使用相同的值。

    你可以试试下面的代码

    <div ng-controller="ValidateCtrl">
        Check Value: <input type="checkbox" ng-true-value="1" ng-false-value="0" ng-model="checkBoxModel"/>
    </div>
    
    Controller
    ---------
    function ValidateCtrl($scope) {
       $scope.checkBoxModel = '1';
    };
    

    所以最初复选框将被选中。

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      相关资源
      最近更新 更多