首页 > 解决方案 > AngularJS,在外部事件上重新初始化(更新页面)

问题描述

在打开正在加载的聊天页面消息后,我有 angularjs 移动应用程序:

myApp.controller('ChatControllerGlobal',function($scope,global) {
    $http({
      method: 'POST',
      url: serverURL+'&act=get_chat',
      withCredentials: true,
    }).then(function successCallback(data) {
        $scope.messages = data.data;
        $scope.loader = false;
        $scope.content = true;
      });

});

现在通过外部事件我需要以某种方式重新初始化控制器(加载新消息):

window.FirebasePlugin.onNotificationOpen(function(data) {
    // some code here to reload new chat messages
});

是否有任何不脏的方法来重新初始化控制器或调用控制器功能?

标签: angularjsfirebasephonegap

解决方案


您可以从 Firebase 插件创建可注入服务。然后将该服务注入您的控制器,并调用一个获取消息的函数:

myApp
  .factory('firebase', function ($window) {
      return $window.FirebasePlugin;
  });

myApp.controller('ChatControllerGlobal', function ($scope, $http, firebase) {
  getMessages();

  firebase.onNotificationOpen(function (data) {
    getMessages();
  });

  function getMessages() {
    $http({
      method: 'POST',
      url: serverURL + '&act=get_chat',
      withCredentials: true,
    }).then(function successCallback(data) {
      $scope.messages = data.data;
      $scope.loader = false;
      $scope.content = true;
    });
  }
});

这样您就可以firebase在单元测试中模拟服务。


推荐阅读