Reputation: 2223
I'm trying to set a checkbox to true with Angularjs. Right now I'm cheating using vanilla javascript to manipulate the DOM, but I want to do it the right way with Angularjs.
Here is the view:
<div x-ng-repeat="addon in addons">
<label for="{{addon.addoncode}}">
<input type="checkbox"
name="{{addon.addoncode}}"
value="{{addon.addoncode}}"
id="{{addon.addoncode}}"
x-ng-model="addon.checked"
x-ng-click="checkAddonDependencies()" >
<span x-ng-bind-html="addon.addon_desc">{{addon.addon_desc}}</span> </label>
</div>
And here is the relevant part of the controller:
if (document.getElementById(dep)) {
document.getElementById(dep).checked=true;
}
The dep value is equal to the addoncode value, so if it exists I check the box. This works and checks the box but how could I do this using the scope instead?
I tried:
x-ng-model="addon.addoncode"
with
$scope.addon.dep = true;
But no luck... any help appreciated. Thanks.
Upvotes: 2
Views: 14440
Reputation: 2223
This turned out to be a simple thing to do. Instead of using the checkbox id:
document.getElementById(dep).checked=true;
I just needed to use the angular filter:
var x = filterFilter($scope.addons, {
addoncode: dep
});
x[0].checked = true;
Upvotes: 0
Reputation: 77920
HTML
<div ng-repeat="addon in addons">
<label for="{{addon.addoncode}}">
<input type="checkbox"
name="{{addon.addoncode}}"
value="{{addon.addoncode}}"
id="{{addon.addoncode}}"
ng-model="addon.checked"
ng-click="checkAddonDependencies()" >
<span ng-bind-html="addon.addon_desc">{{addon.addon_desc}}</span> </label>
</div>
Controller
function countController( $scope, $timeout )
{
$scope.addons = [
{
checked: true
},
{
checked: false
}
];
}
see in Fiddle
[EDIT]
The main point of angular is you don't need to worry about to update HTML. you just need change your $scope.addons
.
you can see how your code works with promises and how you add items every 3 sec to $scope.addons
. I simulated async task by delay
service.
BTW, I didn't touch your HTML
Upvotes: 3
Reputation: 11078
Your object addon
only exists inside the ng-repeat on your template. On the controller you should have something like:
$scope.addons[0].isChecked = true;
As addons is an array. Note that isChecked could take any property name
Then on the template use:
<div x-ng-repeat="addon in addons">
<label for="{{addon.addoncode}}">
<input type="checkbox" x-ng-model="addon.isChecked" x-ng-click="checkAddonDependencies()" >
<span x-ng-bind-html="addon.addon_desc">{{addon.addon_desc}}</span> </label>
</div>
Upvotes: 0