Reputation: 9329
I'd like to set some filter checkboxes as checked in an Angular JS app. I've tried using ng-init
with checked=true
but it isn't working as I'd expect. I want to set all the checkboxes to initially be checked.
http://plnkr.co/edit/AtFGIyoo0h15XMl63aXK?p=preview
I'm fairly new to this but have had a go trying to find the information I'm after. So, now I'm sure that I need to set up the 'checkedness' by setting values inside of my model to begin with. So (this is where I'm certainly totally wrong) I'm using:
$scope.location = ['rural', 'urban', 'coastal']
With checkboxes like so:
<label><input type="checkbox" ng-model="location.rural" class="ng-valid ng-dirty">Rural</label>
<label><input type="checkbox" ng-model="location.urban" class="ng-pristine ng-valid">Urban</label>
<label><input type="checkbox" ng-model="location.coastal" class="ng-pristine ng-valid">Coastal</label>
<hr>
<label><input type="checkbox" ng-model="property_type.pub" class="ng-valid ng-dirty">pub</label>
<label><input type="checkbox" ng-model="property_type.bandb" class="ng-valid ng-dirty">bandb</label>
<label><input type="checkbox" ng-model="property_type.hotel" class="ng-valid ng-dirty">hotel</label>
Here it is in context:
propertyApp.controller('PhoneListCtrl', function ($scope) {
$scope.properties = [
{
title: "Sharrow Bay Hotel",
location:['rural', 'coastal'],
property_type: ['pub']
},
{
title: "The Royal Oak Inn",
location:['rural'],
property_type: ['pub']
},
{
title: "Scale Hill Cottages",
location:['urban'],
property_type: ['hotel']
},
];
$scope.location = ['rural', 'urban', 'coastal']
$scope.title = "Phone list";
$scope.multiplier = 3;
$scope.isEmpty = function (obj) {
return angular.equals({},obj);
};
})
How do I make the checkboxes checked on init?
Upvotes: 0
Views: 583
Reputation: 27976
To start with the ng-model directives should refer to bools in your model and not strings. You can then just initialise these bools to true or false in your controller:
propertyApp.controller('PhoneListCtrl', function ($scope) {
$scope.location = {
rural: true,
urban: true,
coastal: true
}
$scope.property_type = {
pub: true,
bandb: true,
hotel: true
}
});
Also let angular work out what's pristine and dirty for you.
Upvotes: 1