【问题标题】:HTML redirect to AngularJS controller with parametersHTML 重定向到带有参数的 AngularJS 控制器
【发布时间】:2019-12-11 12:36:17
【问题描述】:

我继承了一个烂摊子。我需要快速修复一些需要完全重写的代码 - 但还没有足够的时间进行完全重写。

Orig 开发人员创建了一个 index.js 文件,其中包含所有通过 AngularJS/Ionic 项目使用的各种全局函数。我经常发现特定控制器中的 AngularJS 函数实际上将 $scope/$q 传递给 index.js 文件中的标准 JS 函数 - 它一团糟。

其中一个全局函数是window.FirebasePlugin.onNotificationOpen - 它正在监视任何入站推送通知/消息。最初的开发人员只是对带有数据负载的入站消息使用“警报”。我们现在正尝试重定向这些消息,以便在两个特定页面中属于控制器的适当弹出窗口或模式窗口中打开。

那么问题来了,在全局watch JS函数中,我该如何直接 将“数据/有效负载”传递给控制器​​以在适当的 $scope 中进行处理?

我已修改.state 以接受参数 - 然后所有后续代码都已到位以将 $stateParams 传递给特定控制器:

  .state('tab.clubs', {
      cache: true,
      url: '/clubs',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl',
          params: {
            'pushAction' : 0,
            'pushCode' : 'default'
          }
        }
      }
    })

我遇到的问题是试图弄清楚如何将 URL 数据从标准 JS 传递到 AngularJS .state

全局JS函数:

  window.FirebasePlugin.onNotificationOpen(function(payload) {
    // if there is a payload it will be in payload object
    if (payload.action == 1) {
       window.location("/clubs/", payload) ;  // process message in ClubCtrl
    } else if (payload.action == 2) {
       window.location("/map/", payload) ; // process message in MapCtrl
    }
  }, function(error) {
      console.error(error);
  }) ;

但是这个方法失败了。

【问题讨论】:

  • Uncaught TypeError: window.location is not a function

标签: javascript angularjs ionic-framework parameter-passing


【解决方案1】:

如果您不打算使用 Angulars 路由器导航到页面,则需要以某种方式在 URL 中声明参数。您可以通过/clubs/:pushAction/:pushCode 之类的操作来使用路径参数,或者使用/clubs?pushAction&pushCode 之类的 url 参数来使用

例子:

.state('tab.clubs', {
      cache: true,
      url: '/clubs/:pushAction/:pushCode',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl',
          params: {
            'pushAction' : 0,
            'pushCode' : 'default'
          }
        }
      }
    })

然后导航它

location.href = `/clubs/${payload.action}/${payload.code}`

此外,如果您有很多未知参数,您还可以将整个有效负载作为 base64 编码的 json 传递。我不会推荐这个,但它是......一个解决方案

.state('tab.clubs', {
      cache: true,
      url: '/clubs?state',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl',
          params: {
            'state' : 0,
          }
        }
      }
    })
window.location(`/clubs?state=${btoa(JSON.stringify(payload))}`

然后在您的控制器中反转该操作

class ClubCtrl {
    ...
    // parses the state out of the state params and gives you the full payload
    parseState($stateParams) {
        return JSON.parse(atob($stateParams.state));
    }
    ...
}

它会给你所有的有效载荷,但它很恶心

【讨论】:

  • Uncaught TypeError: window.location is not a function
猜你喜欢
  • 2016-03-23
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
相关资源
最近更新 更多