首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在角模板中使用http cookie值

在角模板中使用http cookie值
EN

Stack Overflow用户
提问于 2015-02-25 21:35:21
回答 2查看 2.9K关注 0票数 0

在我的ASP.NET MVC应用程序中,我有一个精巧的工作。我使用两个具有角度路由的html模板。一个是来自数据库的当前收藏列表,并从我的Web序列化为json,并被angular用于从数据库中列出这些项。

第二个html模板将用于添加新的收藏夹。当包含我的角度代码的整个页面加载时,它有一个名为currentSearch的cookie,它保存着用户执行的最后一个搜索参数的值。

我想将这个值注入到我的角html模板(newFavoriteView.html)中,作为名为和id'd searchString的隐藏输入的值。

我尝试过使用jQuery,但遇到了问题,而且我更愿意在角度内这样做,并以某种方式将值传递给我的模板,或者在视图(模板)中执行工作。然而,我知道后者会是糟糕的形式。下面是我认为对一个人来说很重要的代码,以了解我在做什么。

Index.cshtml (我的ASP.NET视图)

代码语言:javascript
复制
@{
    ViewBag.Title = "Render Search";
    ViewBag.InitModule = "renderIndex";
}
    <div class="medium-12 column">
        <div data-ng-view=""></div>
    </div>
@section ngScripts {
    <script src="~/ng-modules/render-index.js"></script>
}

在MVC控制器中设置cookie

代码语言:javascript
复制
    private void LastSearch()
    {
        string lastSearch = null;
        if (Request.Url != null)
        {
            var currentSearch = Request.Url.LocalPath + "?" + 
                                    Request.QueryString;

            if (Request.Cookies["currentSearch"] != null)
            {
                lastSearch = Request.Cookies["currentSearch"].Value;
                ViewBag.LastSearch = lastSearch;
            }

            if (lastSearch != currentSearch)
            {
                var current = new HttpCookie("currentSearch", currentSearch){ 
                                   Expires = DateTime.Now.AddDays(1) };
                Response.Cookies.Set(current);

                var previous = new HttpCookie("lastSearch", lastSearch) { 
                                   Expires = DateTime.Now.AddDays(1) };
                Response.Cookies.Set(previous);
            }
        }
    }

render-index.js

代码语言:javascript
复制
angular
    .module("renderIndex", ["ngRoute"])
    .config(config)
    .controller("favoritesController", favoritesController)
    .controller("newFavoriteController", newFavoriteController);

function config($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "/ng-templates/favoritesView.html",
            controller: "favoritesController",
            controllerAs: "vm"
        })
        .when("/newsearch", {
            templateUrl: "/ng-templates/newFavoriteView.html",
            controller: "newFavoriteController",
            controllerAs: "vm"
        })
        .otherwise({ redirectTo: "/" });
};

function favoritesController($http) {
    var vm = this;
    vm.searches = [];
    vm.isBusy = true;

    $http.get("/api/favorites")
        .success(function (result) {
            vm.searches = result;
        })
        .error(function () {
            alert('error/failed');
        })
        .then(function () {
            vm.isBusy = false;
        });
};

function newFavoriteController($http, $window) {
    var vm = this;
    vm.newFavorite = {};
    vm.save = function () {
        $http.post("/api/favorites", vm.newFavorite)
            .success(function (result) {
                var newFavorite = result.data;
                //TODO: merge with existing topics
                alert("Thanks for your post");
            })
            .error(function () {
                alert("Your broken, go fix yourself!");
            })
            .then(function () {
                $window.location = "#/";
            });
    };
};

favoritesView.html

代码语言:javascript
复制
<div class="container">
    <h3>New Favorite</h3>
    <form name="newFavoriteForm" ng-submit="vm.save()">
    <fieldset>
      <div class="row">
        <div class="medium-12 column">
          <input name="searchString" id="searchString" type="hidden" 
                 ng-model="vm.newFavorite.searchString"/>
            <label for="title">Name</label><br />
              <input name="title" type="text" 
                     ng-model="vm.newFavorite.name"/>
                <label for="title">Description</label><br />
                <textarea name="body" rows="5" cols="30" 
                          ng-model="vm.newTopic.description"></textarea>
              </div>
              <div class="medium-12 column">
                <input type="submit" class="tiny button radius" value="Save"/> | 
                <a href="/" class="tiny button radius">Cancel</a>
              </div>
          </div>
      </fieldset>
  </form>
</div>

在角加载并抓取cookie并将其填充到隐藏值之后,我的当前图文集一直在页面的末尾使用jQuery。但我没能让它起作用。我还考虑过将值设置为javascript变量(在我的c#页面中),然后使用该变量的角度(一些方式)。我这样做对吗?

还是应该在角度控制器里处理?

我对棱角很陌生,角度范围和一点无知正在阻碍我的前进。如果需要任何其他信息,我可以提供它,如果你能帮助或指导我在正确的方向,谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-25 22:18:58

您可以使用JavaScript读取cookie值,将其设置为$scope对象的属性并在模板上访问它。

代码语言:javascript
复制
//Inside your controllers
function favoritesController($http, $scope) {
    //Get the cookie value using Js
    var cookie = document.cookie; //the value is returned as a semi-colon separated key-value string, so split the string and get the important value

    //Say the cookie string returned is 'currentSearch=AngularJS'
    //Split the string and extract the cookie value

    cookie = cookie.split("="); //I am assuming there's only one cookie set

    //make the cookie available on $scope, can be accessed in templates now
    $scope.searchString = cookie[1];
}

附加注意事项在AngularJS中,作用域是应用程序的控制器和视图之间的粘合剂。控制器和视图共享这个作用域对象。作用域类似于应用程序的模型。由于控制器和视图共享相同的作用域对象,因此可以使用它在两者之间进行通信。作用域可以包含将在视图中运行的数据和函数。请注意,每个控制器都有自己的范围。如果要访问$scope对象,则必须将其注入控制器。

例如:

代码语言:javascript
复制
//inject $http and $scope so you can use them in the controller
function favoritesController($http, $scope) {

可以在视图上访问存储在作用域上的任何内容,还可以从视图中设置范围属性的值。范围对象对于角的双向数据绑定非常重要。

票数 1
EN

Stack Overflow用户

发布于 2015-02-25 21:40:01

对不起,如果我误解或过于简化,but...assuming JavaScript可以读取这个cookie值,您可以让您的控制器读取它并将其分配给$scope变量吗?

如果JavaScript无法读取该值,则可以让ASP将该值写入JavaScript内联脚本标记。不过,这感觉更恶心。

更新以显示控制器-例如。

假设您的HTML看起来有点像这样:

代码语言:javascript
复制
<div ng-controller="MyController as controller">
  <!-- other HTML goes here -->
  <input name="searchString" id="searchString" type="hidden" ng-model="controller.data.currentSearch"/>

那么您的控制器看起来可能如下所示:

代码语言:javascript
复制
app.controller('MyController', function ($scope, $cookies) {
  $scope.data = {
    currentSearch: $cookies.currentSearch
  };
  // Note that the model is nested in a 'data' object to ensure that
  // any ngIf (or similar) directives in your HTML pass by reference
  // instead of value (so 2-way binding works).
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28730090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档