3

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.

JanP
  • 1,579
  • 2
  • 16
  • 27
smchae
  • 1,035
  • 3
  • 17
  • 39
  • 3
    My suggestion is to not do DOM manipulation in your controller – devqon Dec 09 '16 at 09:38
  • @A.Wolff start() function is in another controller for a reason. That is the reason I need to trigger ng-click on open. – smchae Dec 09 '16 at 09:41
  • @devqon Thank you for the advice. But what would be the way to trigger ng-click so I can execute function? – smchae Dec 09 '16 at 09:41
  • Perhaps use $rootScope.$broadcast and a listener in the other controller. If both controllers are on the same level, this will not work. But in that case you can add the $broadcast to a factory and call it from your first controller. – JanP Dec 09 '16 at 10:10

4 Answers4

1

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

JanP
  • 1,579
  • 2
  • 16
  • 27
1

I was able to do this by doing below.

Controller
$scope.$on('modal.shown', function() {
      $rootScope.start();
});

Another Controller
$rootScope.start= function () {
      some code ...
}
smchae
  • 1,035
  • 3
  • 17
  • 39
0

You should try this :

<label class="item">
    <div class="button button-block button-positive" ng-click="start()">info</div>
</label>

In your controller :

$scope.start = function() 
{

}
Rai Vu
  • 1,595
  • 1
  • 20
  • 30
0

You can use ionic model

$ionicModal.fromTemplateUrl('yourmodelhtml.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.confirm = modal;
    });

then call this $scope.confirm to open up on click event.

Rajesh
  • 642
  • 2
  • 7
  • 14