每次加载单页应用程序时检索cookie

时间:2016-07-21 18:57:59

标签: javascript angularjs

需要对下面的AngularJS代码进行哪些具体更改,以便在每次加载页面时检查是否存在名为package main import ( "fmt" ) func main() { var intPointer *int // To set the value use: // intValue := 3 // intPointer = &intValue if intPointer == nil { fmt.Println("The variable is nil") } else { fmt.Printf("The variable is set to %v\n", *intPointer) } } 的Cookie,然后设置myCookie变量成为$rootScope.myCookieValue的价值

代码来自the sample app whose complete code you can explore at this link。这是一个非常简单的示例应用程序,我只想要一个简单的工作解决方案,以便我可以从中构建更复杂的方法。

myCookie

1 个答案:

答案 0 :(得分:1)

你可以在运行程序段中做到这一点我想:

 angular.module('hello', ['ngCookies', 'ngRoute'])

.config(function ($routeProvider, $httpProvider) {

    $routeProvider.when('/', {
        templateUrl: 'home.html',
        controller: 'home',
        controllerAs: 'controller'
    }).otherwise('/');

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.common['Accept'] = 'application/json';

}).run(function ($rootScope, $cookies) {
    var cookieValue = $cookies.get("myCookie");
    if (cookieValue) {
        $rootScope.myCookieVar = cookieValue;
    }
}).controller('navigation',

function ($rootScope, $http, $location, $route) {

    var self = this;

    self.tab = function (route) {
        return $route.current && route === $route.current.controller;
    };

    $http.get('user').then(function (response) {
        if (response.data.name) {
            $rootScope.authenticated = true;
        } else {
            $rootScope.authenticated = false;
        }
    }, function () {
        $rootScope.authenticated = false;
    });

    self.credentials = {};

    self.logout = function () {
        $http.post('logout', {}).finally(function () {
            $rootScope.authenticated = false;
            $location.path("/");
        });
    }

}).controller('home', function ($http) {
    var self = this;
    $http.get('resource/').then(function (response) {
        self.greeting = response.data;
    })
});

我认为你应该使用角度版本> 1.4.x的

你还应该添加引用angular-cookies.js