Molly Harper Molly Harper - 1 month ago 11
Javascript Question

Call function on pageload when ng-checked = true in AngularJS

I am building checkboxes dynamically using Angular. I set the ng-checked value based on a number of conditions.

The checkbox is appropriately checked on pageload. I need to call the makeAddressDefault() function (currently used in ng-click) on page load when ng-checked = true.

<input type="checkbox"
id="defaultAddress{{$id}}"
ng-model="addressChecked"
name="defaultAddress"
ng-click="makeAddressDefault(add, $event)"
ng-checked="addresses.length === 1 || add.IsDefault() || isSelected(add.id)">
<label ng-init="isAddressDefault(addresses, add)" for="defaultAddress{{$id}}">
{{add.FirstName}} {{add.LastName}}<br />
{{add.Address1}}<br />
{{add.City}}, {{add.State}} {{add.ZIP}}
</label>


What is the best way to handle this? Thanks!

Answer

In your controller why don't you do something like

$scope.init = function(){
  angular.forEach(addresses, function(add){
    if(addresses.length === 1 || add.IsDefault() || isSelected(add.id)){
        makeAddressDefault(add)
    }
  })
}

$scope.init()

It will automatically call your init function once the controller has been initialized.

Comments