Search code examples
javascriptjqueryionic-frameworkionic-view

Ionic trigger click event does not work


I have a modal in my Ionic app and when modal is shown, I want to trigger click event on specific element.

Controller
$scope.$on('modal.shown', function() {
      document.getElementById('somemodal').click(); // #1
      $( "#somemodal" ).triggerHandler( "click" );  // #2
});


Index.html
<h1 class="title" id="somemodal" ng-click="start()">info</h1>

Both #1 and #2 do not trigger ng-click which triggers function start in another controller.

Any suggestion or advice would be appreciated.

Thank you.


Solution

  • If both controllers are on the same level, use a factory like:

    (function() {
        'use strict';
    
        angular
            .module('yourapp')
            .factory('yourfactory', yourfactory);
    
        yourfactory.$inject = [$rootScope];
    
        /* @ngInject */
        function yourfactory($rootScope) {
            var service = {
                start: start
            };
            return service;
    
            function start() {
                $rootScope.$broadcast('dostart', {});
            }
         }
    })();
    

    Then in Controller 1 (with the modal):

    $scope.$on('modal.shown', function() {
          yourfactory.start(); // Don't forget to inject yourfactory
    });
    

    And in Controller 2:

    $scope.$on('dostart', function(event, args) {
        $scope.start();
    });
    

    If both controllers are not on the same level, it is also possible to do a direct $broadcast or $emit from your first controller without a factory, depending on the hierarchy of your controllers