Search code examples
ionic-frameworkionic-popup

Ionic blank project popup message issue


As per the my requirement i want to show a popup message when opening the App. can't use alert.

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function($scope, $ionicPopup, $timeout) {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

	 $scope.showAlert = function() {
	   var alertPopup = $ionicPopup.alert({
		 title: 'Don\'t eat that!',
		 template: 'It might taste good'
	   });

	   alertPopup.then(function(res) {
		 console.log('Thank you for not eating my delicious ice cream cone');
	   });
	};

	if (window.cordova) {
		cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
			if(!enabled){
				alert("Location is not enabled");
				cordova.plugins.diagnostic.switchToLocationSettings();
			}
		}, function(error) {
			alert("The following error occurred: " + error);
		});
	}
  });
})

But this is giving an error " $scope is undefined".


Solution

  • $scope is not provided in run function. Therefore, you can only inject $rootScope to run function. Replace the $scope with $rootScope and you will be doing fine.

    .run(function($ionicPlatform, $rootScope, $ionicPopup, $timeout) {
        $ionicPlatform.ready(function() {
    
        // Code here
        ....
    
        $rootScope.showAlert = function() {
           var alertPopup = $ionicPopup.alert({
             title: 'Don\'t eat that!',
             template: 'It might taste good'
           });
    
           alertPopup.then(function(res) {
             console.log('Thank you for not eating my delicious ice cream cone');
           });
        };
    
        // Code here
        ....
    });
    
    <button ng-click="$root.showAlert()">