automatically click button after page load in angularjs [duplicate]

岁酱吖の 提交于 2019-12-06 08:52:04

One way to do it can be a custom directive. Directive onLoadClicker in the attached snippet clicks the element on which it is defined once the directive is rendered - in your case on the page load.

The ng-click="wasClicked()" is there just for control that it was really clicked, see browser console. That's also why I defined priority of -1, because ng-clicks priority is 0.

You just need to provide your logic (wrap the $timeout in an if()) on when to do it and when not to (for example based on routeParams).

Note: $timeout is there to make Angular world aware of the click (will run digest cycle), without it Angular would not notice something happened.

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', ['$scope',
  function($scope) {
    $scope.wasClicked = function() {
      console.log('I was clicked!');
    }
  }
]);

myApp.directive('onLoadClicker', ['$timeout',
  function($timeout) {
    return {
      restrict: 'A',
      priority: -1,
      link: function($scope, iElm, iAttrs, controller) {
        $timeout(function() {
          iElm.triggerHandler('click');
        }, 0);
      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <a href="" ng-click="wasClicked()" on-load-clicker>link</a>
</div>

If you are trying to call a function during onload , then try this

var init = function () {
   // check if there is query in url
   // and fire search in case its value is not empty
};
// and fire it after definition
init();


// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!