Dean Christian Armada Dean Christian Armada - 5 months ago 44
AngularJS Question

Trigger Event Click upon page load

I do not know why I can not trigger a click event on my controller upon page load. What I want is the checkboxed to be click literally.

<!DOCTYPE html>
<html >

<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>

<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-model="dean" ng-click="btnChange($event, values, 1)" id="one" name="one" class="here" >
<input type="checkbox" ng-model="armada" ng-click="btnChange($event, values, 2)" id="two" name="one" class="here" >
<!--<p ng-repeat="btn in btns">-->
<!-- <input type="checkbox" ng-model="btn.bool" class="here" > {{ btn.value }}-->
<!--</p>-->
{{btn }}
{{values }}
</div>
<script type="text/javascript">
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [{}, {}, {}];
$scope.values = [];
$scope.btnChange = function(event, model, val){
_this = angular.element(event.target);
x = _this.prop("checked");
if(x){
model.push(val);
}else{
index = model.indexOf(val);
model.splice(index, 1);
}
};
angular.element("#one").triggerHandler("click");
}]);
</script>
</body>
</html>


Here is the plunker: http://plnkr.co/edit/7DpCvkKLlKhRc3YwFTq0?p=preview

Answer

I see that you have used jQuery on the page. So you can simply do this :

 $(function(){
     angular.element("#one").trigger("click"); 
 });

A complete jQuery solution would be :

 $(function(){
    $("#one").click(); 
 });

A complete angular solution would be (like others mentioned) :

angular.element(document).ready(function() {
    angular.element("#one").trigger("click"); 
}); 

http://plnkr.co/edit/0OHDIVB2JGqDZnF56E6M?p=preview

You are triggering the code to click when the document is not completely ready/rendered so you need to wait till the entire document(or in this case, your checkbox) is loaded and only then you can perform actions on your elements.

Comments