【问题标题】:AngularJS, reinit (update page) on external eventAngularJS,在外部事件上重新初始化(更新页面)
【发布时间】:2018-10-29 18:22:53
【问题描述】:

我有 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
});

有没有什么不脏的方法来重新初始化控制器或调用控制器函数?

【问题讨论】:

  • 旁注:我不确定您是否有特殊情况要求您不使用像 $http 这样的内置服务,但仅供参考,如果您使用 $http 及其承诺,您将不会不必做$scope.$apply()
  • @FrankModica,更新了代码,现在看起来更有棱角 =)

标签: angularjs firebase phonegap


【解决方案1】:

您可以从 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 服务。

【讨论】:

  • 遇到了一个问题,我需要在多个控制器中接收这些通知,我将在几个地方定义firebase.onNotificationOpen(function (data) {,所有以前的控制器都停止工作......
  • 对,现在您可以在任何需要的地方拨打onNotificationOpen。这不是很好吗?
  • 我换了一种方式,因为onNotificationOpen 在最后一次声明时只触发一次,所以我必须创建自定义事件并从 onNotificationOpen %) 触发它
猜你喜欢
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2014-12-02
  • 2019-08-23
  • 1970-01-01
相关资源
最近更新 更多