Issue with Angular Ionic badge count not refreshing properly

I'm a beginner with Angular and I feel like I'm struggling to grasp the digest cycle. I'm attempting to update a badge count within an ion-tab (using Ionic).

"ion-tab"

<ion-tab title="Requests" badge="data.badge" ng-controller="RequestTabCtrl" badge-style="badge-assertive" icon-off="ion-pull-request" icon-on="ion-pull-request" href="#/tab/requests">
<ion-nav-view name="tab-requests"></ion-nav-view>

I've created a factory that stores an array, which gets updated via socket.io.

"notifications factory"

.factory('notifications',function(){
  var list = [];
  return{
    all: function(){
      return list;
    },
    add: function(data){
      list.push(data);
    },
    length: function(){
        return list.length;
    }
  };
});

.controller('RequestTabCtrl',function($scope,notifications){
  $scope.data = {
    badge : notifications.length()
    };
});

The issue I'm facing is that the badge count doesn't update when the notifications array changes through socket.io updates. I have confirmed that the array is being appropriately updated. I can even log the array length and see it changing. Additionally, I've set a scope variable in the ion-tab's child io-nav-view, so I can observe the expression {{requests.length}} updating in that view.

.controller('RequestsCtrl', function($scope,notifications) {
  $scope.requests = notifications.all();
})

I've attempted using $watch (within RequestTabCtrl) on notifications.length. I've also tried calling $apply (within RequestTabCtrl), resulting in a "$digest already in progress" error. Furthermore, I experimented with $timeout without seeing any positive outcome (both in RequestTabCtrl and the factory length function). Any help would be greatly appreciated.

Answer №1

Special thanks to AjinderSingh for helping us find the solution.

There are two ways we can tackle this issue. The first approach involves using the $interval method:

.controller('RequestTabCtrl',function($scope,notifications,$interval){
    $interval(function(){
       $scope.data = {
           badge : notifications.length()
        };
    },2000);
});

The second approach is to use $broadcast from the factory when an item is added to the array, and then catching this event in the controller:

.factory('notifications',function($rootScope){
  var list = [];
  return{
    all: function(){
      return list;
    },
    add: function(data){
      list.push(data);
      $rootScope.$broadcast('update');
    },
    length: function(){
        return list.length;
    }
  };
});


.controller('RequestTabCtrl',function($scope,notifications,$interval){
      $scope.$on('update',function(){
           $scope.data = {
              badge : notifications.length()
            };
       });
 });

I have decided to go with the second approach as it appears to be more organized and efficient.

Answer №2

When the $ionicPlatform is ready, the $cordovaBadge.promptForPermission() function is called.
    
$scope.setBadge function is defined to set a badge value. It first checks if the permission has been granted using $cordovaBadge.hasPermission(). If permission is granted, it sets the badge value using $cordovaBadge.set(). If not, an error alert is shown.

$ionicPlatform.ready(function() {
    $cordovaBadge.promptForPermission();

    $scope.setBadge = function(value) {
        $cordovaBadge.hasPermission().then(function(result) {
            $cordovaBadge.set(value);
        }, function(error) {
            alert(error);
        });
    }
});

For more information, please visit

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

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

Make AutoComplete rely on the outcome of something else

I want to create two AutoComplete textboxes where the second textbox depends on the value input in the first one. Full AutoComplete: <script> var stateId = 0; $(document).ready(function () { $.ajax({ dataTyp ...

Is it possible to add a click handler function to a dynamically generated link in Vue?

When working with Vue components, I receive dynamic messages from the server: module.exports = { data() { return: { windowText: '' } }, methods: { showCancelEntrieWindow(){ this.$http.post('/page', {'number& ...

Struggling to navigate web pages with Selenium using Java is proving to be a challenge

I am currently working on using Selenium's HtmlUnitDriver and WebElement classes in Java to automate clicking the "Download as CSV" button on Google Trends. The issue that I am encountering is that the button remains hidden until another settings men ...

Can an HTML select box have a horizontal scroll bar added to it?

I am facing an issue with the following HTML code. <!DOCTYPE html> <html> <body> <select> <option value="volvo">Volvoooooooooooooooootooooooolargeeeeeeeeeeee</option> <option value="saab">Saab& ...

Displaying two div elements horizontally using Material-UI

Can the styled utility from mui be used to align 2 divs side by side? The documentation examples don't seem to cover this specific scenario. While answers on this and this address it, they don't relate to mui / material ui. I attempted the fol ...

Click on a table cell in Vue to display its corresponding data in a modal

I have successfully implemented a modal in my Vue component that works well with static text inside it, confirming its functionality. However, when attempting to pass data from the table cell that is being clicked into the modal, I encountered an error st ...

Resize drop zone with drag and drop functionality

I am using jQuery for dragging and dropping elements, but I am facing an issue. When I resize the drop zone while starting to drag an item, it seems like the previous size of the drop zone is still being used as the space. Is there a way to fix this? ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

Executing a function by clicking on an element with the `ng-click` directive within a Bootstrap modal

I'm working on an app that allows users to submit posts for review. When a user clicks the add post button, I have a Bootstrap modal pop up to confirm their choice. Within this modal, there is a "confirm" button that should trigger a function. Strang ...

How to deselect a checkbox using AngularJS

I have a checklist of items <input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/> and I need to unselect the currently selected checkbox $scope.toggleSelection = function toggl ...

Instructions on assigning a date string value (retrieved from the database) to the <input type="date" ng-model="endtime" name="endtime" /> field

Hey there! I'm new to using angularjs and I'm facing some issues. I have a list of data where, when updating a row, the row value should be added to a table with a datetime column. However, when I try to edit it, I can't seem to set the valu ...

The mousedown event does not seem to function properly on dynamically added text elements

When two texts are enclosed in p tags, my goal is to create an interactive function where clicking on one text causes it to move slightly and the other text to be temporarily deleted. However, when the deleted text is re-added after clicking on the first t ...

Displaying Angular table rows with missing values (Error: Cannot access property 'length' of undefined)

In the view, I have a table displaying nested data using ng-repeat. I want to show only rows with empty cells (<textarea>) when a link is clicked to apply a filter. The text of the link should change to 'Show all data' so that clicking it a ...

The format for a DateTime field in a JSON string array is as follows: yyyy-MM-dd hh:mm:ss

I am working with a JSON array string pulled from a database and I need to format the DateAndTime field into yyyy-MM-dd hh:mm:ss. This formatting needs to be flexible as the data passed through will vary, except for the DateAndTime. Here is my current att ...

Is there a way to access the variable value chosen from a select dropdown inside a function and then assign it to a JavaScript variable outside of the function?

Below is the HTML and JavaScript code that I am working with: function changeResult() { x = document.getElementById("dropdown-list").value; console.log((x)); } var qq; <select id="dropdown-list" onchange="changeResult()"> <option value="4 ...

Fullcalendar JS will easily identify dates with events, allowing users to simply click on those dates to redirect to a specific URL

When looking at the official example, we can see that the events are displayed in a typical calendar format: https://fullcalendar.io/js/fullcalendar-3.5.0/demos/basic-views.html Each event is listed in the calendar, and clicking on an individual event wi ...

How to Effectively Incorporate JavaScript into Selenium?

After much searching and deliberation, I am still struggling to grasp the process of integrating Javascript into Selenium IDE. While recording a test case, I hit a roadblock where I can't progress further without incorporating scripts. Specifically, I ...

Can someone explain how to iterate through an array to find a specific value using CoffeeScript?

Having trouble extracting the full_name value from an array using CoffeeScript. Despite extensive research on Stack Overflow and CoffeeScript's docs, I haven't been able to solve it. Here is my current code. Can someone help me identify what&apos ...