如何在不使用localstorage的情况下将php响应数据从一个页面传递到angularjs中的另一个页面

时间:2016-06-16 11:39:04

标签: angularjs

我有一个疑问,如何在不使用localstorage的情况下将数据从一个页面传递到angularjs中的另一个页面,即使用户重新加载该页面,数据也应该存在。

这里有没有出路?

提前感谢

3 个答案:

答案 0 :(得分:0)

您可以使用Cookie' s:

https://docs.angularjs.org/api/ngCookies/service/ $饼干

您可以参考此JSbin链接,例如:

http://jsbin.com/duxaqa/2/edit

此外,还有一个很好的stackoverflow答案,符合我的需求,我想的是一个比我更完整的解释:

How to access cookies in AngularJS?

答案 1 :(得分:0)

您可以将数据放入Cookie

// set cookie on one page:
setCookie("key", value);

// get cookie on another page:
var val = getCookie("key");

使用功能:

function setCookie(name, value, options) {
  options = options || {};

  var expires = options.expires;

  if (typeof expires == "number" && expires) {
    var d = new Date();
    d.setTime(d.getTime() + expires * 1000);
    expires = options.expires = d;
  }
  if (expires && expires.toUTCString) {
    options.expires = expires.toUTCString();
  }

  value = encodeURIComponent(value);

  var updatedCookie = name + "=" + value;

  for (var propName in options) {
    updatedCookie += "; " + propName;
    var propValue = options[propName];
    if (propValue !== true) {
      updatedCookie += "=" + propValue;
    }
  }

  document.cookie = updatedCookie;
}

function getCookie(name) {
  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

但请记住,Cookie大小有限:每个域4093个字节。

答案 2 :(得分:0)

您可以使用$ rootScope或$ cookieStore将数据传递到另一个页面。但是,只有$ cookieStore才会在用户重新加载页面时保存数据。看看如何实现示例:

angular.module('cookieStoreExample')
.controller('ExampleController', function($cookieStore) {
  // Put cookie
  $cookieStore.put('myFavorite','oatmeal');
  // Get cookie
  var favoriteCookie = $cookieStore.get('myFavorite');
  // Removing a cookie
  $cookieStore.remove('myFavorite');
});