我整理了一个非常简单的示例,说明如何从以 Angular 检查的复选框中触发函数,并让该函数检查以查看复选框的新值并相应地显示或不显示一个消息。它有效,但只有在我选中并取消选中该框至少一次之后。出于这个原因,我认为我只需将复选框值默认为 false 即可解决问题,但事实并非如此。任何人都可以帮助我调整它以使其正常工作,如果是这样,也许可以解释为什么我的想法有缺陷,我对 $scopes 状态不理解什么。顺便说一句,它也会翻转,这意味着当我选中该框时,该消息就会消失,而当我取消选中它时,它会说它已选中。
我做这些练习是为了更好地了解 Angular 是如何工作的,我内心深处知道这是一个 javascript 问题,但我仍然没有弄清楚。感谢任何帮助
app.js
var formApp = angular
.module('formApp', [])
.controller('formController', function($scope) {
$scope.formData = {};
$scope.redCheckFunction = function() {
if ($scope.formData.favoriteColors.red == true){
$scope.redMessage = "red is checked";
} else {
$scope.redMessage = "";
}
};
});
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div>
<h2>Angular Checkboxes</h2>
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
ng-model="formData.name">
<label>Description</label>
<input type="text" class="form-control" name="description"
ng-model="formData.description">
</div>
<!-- MULTIPLE CHECKBOXES -->
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.red"
ng-init="favoriteColors.red.disabled=false"
ng-click="redCheckFunction()"> Red
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.blue"> Blue
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.green"> Green
</label>
</div>
<button type="submit" class="btn btn-danger btn-lg">Send Away!</button>
<h2>{{redMessage}}</h2>
</form>
<h2>Sample Form Object</h2>
<pre>
{{ formData }}
</pre>
</div>
</body>
</html>
我创建了一支笔来让事情变得更容易: Checkbox Pen
最佳答案
ng-click is fired before the model is updated :
Note that ngClick events will occur before the model is updated.
您需要使用ng-change 指令:
Evaluate the given expression when the user changes the input.
http://codepen.io/anon/pen/azaJob
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red" ng-init="formData.favoriteColors.red.disabled=false" ng-change="redCheckFunction()"> Red
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.blue"> Blue
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.green"> Green
</label>
</div>
当您输入函数 redCheckFunction
时,该值已更新。
关于javascript - 指示在 Angular 中选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28913564/