簡體   English   中英

如何使用AngularJS在數據庫的復選框中設置默認值

[英]How to set default value checked in a checkbox from database using AngularJS

編輯記錄時,數據會在各自的字段中進行編輯,但如果其值為1則不會選中該復選框。

它應該處於檢查狀態,如果它有1並且沒有檢查它是否為0因為該字段的數據類型是tinyint 我正在通過PHP從JSON數組中檢索數據。 我試圖通過ng-checked="{{rec.isSpecial}}"獲得價值,但它無效。

這是我的HTML:

 <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <div class="checkbox c-checkbox"> <label> <input type="checkbox" ng-checked="{{rec.isSpecial}}" ng-model="rec.isSpecial"> <span class="fa fa-check"></span>Special </label> </div> </div> </div> 

這是我的JS

$scope.rec = $resource('api/AdminArea/category/edit/:id', {
  id: id
}).get(function(data) {
  $scope.rec = data;
});

由於您的數據返回數字而不是true或false值,您可以這樣做:

<div class="form-group">
    <div class="col-lg-offset-2 col-lg-10">
      <div class="checkbox c-checkbox">
        <label>
          <input type="checkbox" ng-checked="rec.isSpecial==1" ng-model="rec.isSpecial">
          <span class="fa fa-check"></span>Special
        </label>
      </div>
    </div>
  </div>

請參閱小提琴了解更多信息

您根本不需要進行ng-checkedng-model足以使其工作。 如果您的rec.isSpecial設置為1以便進行檢查,那么只需input如下:

<input type="checkbox" ng-model="rec.isSpecial" ng-value="1" />

並且Angular會自動檢查該復選框。

表達式ng-checked={{ ... }}需要一個truefalse語句。 如果你設置rec.isSpecial = true ,在你的Angular控制器中,你的代碼應該可行!

 'use strict'; var app = angular.module('MyApp',[]); app.controller('myController', function ($scope) { $scope.isSpecial =true; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="form-group" ng-app ="MyApp" ng-controller="myController"> <div class="col-lg-offset-2 col-lg-10"> <div class="checkbox c-checkbox"> <label> <input type="checkbox" ng-checked="{{isSpecial}}" ng-model="isSpecial"> <span class="fa fa-check"></span>Special </label> </div> </div> </div> 

如果在標簽輸入中使用ng-model ,則實際上不需要指令ng-checked

由於它是一個復選框,因此模型將是一個布爾值,因此您需要進行轉換。 這個例子可行

HTML

<div data-ng-app="app">

  <div data-ng-controller="MainController">
    Check
    <input type="checkbox" data-ng-model="isSpecial">
  </div>
</div>

JS

angular.module('app', []);

angular.module('app')
    .controller('MainController', mainController);

mainController.$inject = ['$scope'];

function mainController($scope){

  $scope.check = 0;
  $scope.isSpecial = ($scope.check === 1) ? true : false;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM