Unfortunately, the rootScope cannot be accessed within the window.onnotification function

In my code, I am attempting to set up $rootScope as a global variable so that it can be accessed in the controller.

Here is an excerpt from app.js:

angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.services', 'app.directives'])
.run(function($ionicPlatform,$rootScope) {
  $ionicPlatform.ready(function() {
  
    // Some code here...
    
    pushNotification = window.plugins.pushNotification;
    pushNotification.register(
      onNotification,
      errorHandler,
      {
        'badge': 'true',
        'sound': 'true',
        'alert': 'true',
        'ecb': 'onNotification',
        'senderID': '999999999999',
      }
    );

  });
})

window.onNotification = function(e){

      // Switch statement and logic here...

};

window.errorHandler = function(error){
  // Error handling logic...
}

Although I am able to retrieve the device_token and display it in an alert, I am running into issues when trying to access it through $rootScope in the controller.

Here is some related code from Controller.js:

angular.module('app.controllers', [])

.controller('onWalletWelcomesCtrl', function($scope, $ionicModal,User,$ionicLoading,$rootScope) {

    $ionicModal.fromTemplateUrl('signup-modal.html', {
      id: '1',
      scope: $scope,
      backdropClickToClose: false,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.oModal1 = modal;
    });

    $scope.proceed = function(){
        alert($rootScope.devicetoken);
        $ionicLoading.show({template: '<ion-spinner icon="android"></ion-spinner>'});

    }

})

Unfortunately, I am receiving 'undefined' when trying to alert the devicetoken in the proceed function. I need guidance on how to properly utilize $rootScope within the window.onNotification function to successfully pass the devicetoken to the controller. Any suggestions on best practices for sharing variables would be greatly appreciated.

Answer №1

To ensure your

window.onNotification = function(e){..}
declaration functions properly, it must be placed within your
.run(function($ionicPlatform,$rootScope) {...}
block.

If you leave it outside of the run() block, $rootScope will be undefined in your onNotification handler. By declaring the onNotification handler inside the run() block, it will have access to the rootScope object while it is being defined.

Additionally, since the event handler lives outside the angular lifecycle, you need to manually trigger a new digest cycle. To do this, wrap your

$rootScope.devicetoken = device_token;
line with a $rootScope.apply() in your notification handler like so:

$rootScope.apply(function(){
      $rootScope.devicetoken = device_token;
});

Answer №2

When utilizing $rootScope within the function window.onNotification, it operates outside of the Angular context. To ensure updates are applied correctly, you must instruct Angular to perform the update by including $scope.$apply(); after updating the $rootScope.

Answer №3

Ensure to set the value of $rootScope.devicetoken dynamically within the run scope

.run(function($ionicPlatform,$rootScope) {
    $rootScope.devicetoken = '';

Confirm that window.onNotification is triggered prior to proceeding with $scope

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Process executes another process

Can anyone assist me with a JavaScript inquiry? I am curious if it is feasible to implement this: variable: { info1: 'info1', info2: 'info2', show: false, someNameFunction: functionWhichIWantRun(row) } So, after defining the var ...

Top method for utilizing render props in React

Currently, I am employing render model props. However, I have a hunch that there might be an alternative method to achieve the same outcome. Is anyone familiar with another approach? {variable === "nameComponen" && <component/>} {variable === "name ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Ionic Serve malfunctioning, displaying blank page

Currently, I am in the process of developing an application using the Ionic framework. While attempting to inject a function into a state in a .js file associated with one of the pages in my application, I encountered a strange issue. Upon running Ionic S ...

Click the button to automatically insert the current time

Hello, I am new to scripting and seeking some guidance. I have a code that retrieves the current time and sends it to a MySQL database when a button is clicked. <form action="includes/data_input.inc.php" method="POST"> <!-- button - Start ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

The mysterious case of the vanishing close button on Curator.io's mobile

Currently, I am using curator.io aggregator to showcase my Instagram feed on the website. An issue arises when switching to mobile view as the close button (class="crt-close") disappears. You can see an example of this here: To replicate the pr ...

Error: The function $translate.use is not available

I initially included the languages en, fr & nl in my app.js file. Realizing this was not a good practice, I moved the translations out of the app.js file and placed them in JSON formatted files. However, upon loading the site now, I encountered a TypeErro ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

The Ionic v1 HTML5 video player displays a black screen while the audio continues to play

I am encountering an issue with my Ionic v1 app that features an HTML5 video player pulling from an API. After playing the app for 2-3 minutes, the screen goes black on Android while the audio continues to play. How can I resolve this problem? HTML: < ...

Understanding the behaviour of injecting attributes in directive scopes

Can anyone provide some insight on why my JavaScript key code isn't working as expected in the second directive of my example below? It seems that injecting scope attributes is causing the function passed into the directive not to be evaluated properl ...

What is the best way to arrange integers in numerical order using ng-repeat?

I have a list that is displayed in numerical order by id using the code below: <dl class="dl-horizontal" ng-repeat="projectManager in projectManagers| orderBy: 'id'"> <dt>{{projectManager.id}}</dt> ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Difficulty encountered in closing div by clicking the background with the help of jquery

I am facing a challenge with properly closing a div container and restoring it to its original state when I click outside of it. Despite trying various solutions from stackoverflow and extensive internet research, I have been unable to find or come up with ...

Only one active class is allowed in the Bootstrap Accordion at any given time

I have implemented Bootstrap's accordion on my webpage, consisting of two different sections with unique content. Upon loading the page, the active class defaults to the first element of the first section. However, if I navigate to the "Second" sectio ...

Leveraging fullcalendar.io alongside JSONP

I'm currently in the process of integrating public holidays into my FullCalendar application. You can check out FullCalendar here. var actionUrl = @Html.Raw(Json.Encode(@Url.Action("Calendar", "Lecture"))); $('#fullcalendar').ful ...

What is the best way to showcase only the most recent data that has been received

Hey there, I'm working on a way to display only the most recent message of the day, However, I'm facing an issue where my code is always selecting the first message instead of the latest one. Even though it's not the initial object in the ...

Passing the initial value from a PHP array to Ajax using an HTML element

I am currently dealing with an HTML form that fetches values from an array list. The form is submitted using Ajax along with a PHP script. However, I am encountering an issue where clicking on different array items only submits the first value in the array ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Dynamic Vue2 input field names

With Vue2, I am attempting to create input tags with dynamic content. My attempts at binding it to a function using :name="someFunction" have been unsuccessful in this case. The name attribute needs to be in the format people[0]['name'] people ...