我知道也有类似的问题,但是此复选框位于表单内。如何在加载时默认选中复选框“订阅”?
这是我的HTML的一部分:
<div ng-app="app9" ng-cloak>
<div ng-controller="userCtrl">
<form name="userForm" ng-submit="saveUser(userInfo)">
<label>First Name :</label>
<input type="text" name="fname" ng-model="userInfo.fName"/>
<br />
<label>Last Name :</label>
<input type="text" name="lname" ng-model="userInfo.lName"/>
<br />
<label>Street :</label>
<input type="text" name="street" ng-model="userInfo.street"/>
<br />
<label>Subscribe :</label>
<input type="checkbox" name="subscribe" ng-model="userInfo.subscribe" />
<br />
<label>Delivery Method :</label>
<select name="delivery" ng-model="userInfo.delivery" ng-required="true" >
<option value="Email">Email</option>
<option value="Mail">Mail</option>
</select>
<br /><br />
<input type="submit" value="Save" ng-disabled="userForm.$invalid"/>
<ul>
<li ng-repeat="item in user">
{{'User: ' + item.fName + ' ' + item.lName + ' ' + item.street + ' ' + item.subscribe + ' ' + item.delivery}}
</li>
</ul>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<script src="js/exam9.js"></script>
</body>
这是我的JavaScript考试:9。
var app9 = angular.module('app9', []);
app9.controller('userCtrl', function ($scope) {
userInfo.subscribe = true;
$scope.saveUser = function (userInfo) {
if ($scope.userForm.$valid) {
$scope.user.push({
fName: userInfo.fName,
lName: userInfo.lName,
street: userInfo.street,
subscribe: userInfo.subscribe,
delivery: userInfo.delivery
});
console.log("User saved");
} else {
console.log("Error: Couldn't save user")
}
}
});
我尝试了userInfo.subscribe = true和$ scope.userInfo.subscribe = true。
更新:对不起,它可能是一个重复的问题。它对我不起作用的原因是因为我原来有这个:
<input type="checkbox" name="subscribe" ng-model="userInfo.subscribe" ng-true-value="'Subscribe'" ng-false-value="'Don\'t Subscribe'"/>
以下对我不起作用:
$scope.userInfo = {};
$scope.userInfo.subscribe = true;
应为:
$scope.userInfo = {};
$scope.userInfo.subscribe = 'Subscribe';
答案 0 :(得分:2)
您应该先在$ scope上声明userInfo对象。
使用以下代码对我有用:
var app9 = angular.module('app9', []);
app9.controller('userCtrl', function ($scope) {
$scope.userInfo = {};
$scope.userInfo.subscribe = true;
$scope.saveUser = function (userInfo) {
if ($scope.userForm.$valid) {
$scope.user.push({
fName: userInfo.fName,
lName: userInfo.lName,
street: userInfo.street,
subscribe: userInfo.subscribe,
delivery: userInfo.delivery
});
console.log("User saved");
} else {
console.log("Error: Couldn't save user")
}
}
});