角度离子徽章计数未更新

Angular ionic badge count not updating

本文关键字:更新 徽章      更新时间:2023-09-26

我是angular的新手,相信我还没有完全理解摘要周期。我正在尝试更新离子标签中的徽章计数。(使用离子(

"离子标签">

<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>

我写了一个工厂,将存储和数组。这个数组是通过socket.io 更新的

"通知工厂">

.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()
    };
});

我的问题是,当通过socket.io更新通知数组时,徽章计数没有更新。我已经检查了数组是否正在更新。事实上,我可以控制台记录数组的长度,并可以看到它的变化。此外,我在ion选项卡的子导航视图中设置了一个范围变量,因此可以在该视图中看到表达式{requests.length}}的更新。

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

我在notifications.length上尝试过$watch(在RequestTabCtrl中(。我尝试过调用$apply(在RequestTabCtrl中(,这导致$digest已经在进行中。我尝试过$timeout,但没有看到任何积极的结果(在RequestTabCtrl和factory-length函数中(。非常感谢你的帮助。

多亏了AjinderSingh,才找到了解决方案。

所以有两种方法。首先使用$interval方法:

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

第二种方法是在将一个项目添加到数组后从工厂进行$broadcast。然后在控制器中捕获此事件:

.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()
            };
       });
 });

我选择了第二种方法,因为它看起来更干净。

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

完整参考plz检查https://www.thepolyglotdeveloper.com/2015/07/modify-the-badge-number-of-an-ionic-framework-app/