javascript 我应该如何将数据从服务器端控制器传递给 AngularJS 控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22262841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:47:55  来源:igfitidea点击:

How am I supposed to pass data from serverside controller an AngularJS controller?

javascriptangularjsasp.net-mvcangularjs-controllerng-init

提问by Ben Aaronson

I've encountered what I believe to be a common scenario, in which I am using an MVC pattern (specifically ASP.NET's MVC framework) for a web application, with AngularJS on the front-end. My problem is that I have a particular value which is part of the model getting passed to my view, which I also want to make available to my Angular controller's $scope, ideally as soon as the controller is initialized.

我遇到过一种我认为很常见的情况,在这种情况下,我将 MVC 模式(特别是 ASP.NET 的 MVC 框架)用于 Web 应用程序,前端使用 AngularJS。我的问题是我有一个特定的值,它是传递给我的视图的模型的一部分,我也希望它可用于我的 Angular 控制器的 $scope,理想情况下,一旦控制器初始化。

How to do this is a question that has been asked and answered before. There's an obvious candidate for it: ngInit. However, at some point Angular updated their documentationwith what appears to be a warning against this specific thought:

如何做到这一点是之前有人问过和回答过的问题。有一个明显的候选者:ngInit. 然而,在某些时候 Angular 更新了他们的文档,似乎是对这个特定想法的警告:

The only appropriate use of ngInitis for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInitto initialize values on a scope.

唯一合适的用途ngInit是为 的特殊属性设置别名ngRepeat,如下面的演示所示。除了这种情况,您应该使用控制器而不是ngInit初始化范围上的值。

The suggested alternative isn't very relevant.

建议的替代方案不是很相关。

Of course, there are other workarounds I can think of. The view could insert the value into an ngModeldirective on a hidden input, for example. Or I could just plain ignore the warning and use ngInitanyway. But any that I can think of are either an uglier way of doing the same thing as ngInit, or clearly worse.

当然,我还能想到其他解决方法。例如,视图可以将值插入到ngModel隐藏输入的指令中。或者我可以直接忽略警告并使用ngInit。但是我能想到的任何方法要么是做同样事情的ngInit更丑陋的方式,要么显然更糟。

Ultimately the fact that what seems like the obvious solution to me is apparently the wrong one is probably an indicator that my mindset isn't in tune with how Angular is supposed to be done. So my question isn't "how do I deal with this scenario", instead it's:

最终,对我来说似乎显而易见的解决方案显然是错误的这一事实可能表明我的心态与 Angular 应该如何完成不一致。所以我的问题不是“我如何处理这种情况”,而是:

  1. How am I supposedto deal with, or avoid, this scenario?
  2. Why am I not supposed to use ngInit?
  1. 应该如何处理或避免这种情况?
  2. 为什么我不应该使用ngInit

A clarification, since from the first two comments this isn't clear: This is for a situation where some or most of the page is being served directly as the MVC view, with only some particular piece of functionality being provided by Angular. The data that I want to pass to my Angular controller is already passed to the view in the model. I don't want the Angular controller to then go and have to do its own get request to the server just to get the same parameter that's already available to the view in a different format.

澄清一下,因为前两条评论并不清楚:这是针对部分或大部分页面直接作为 MVC 视图提供服务的情况,Angular 仅提供某些特定功能。我想传递给 Angular 控制器的数据已经传递给模型中的视图。我不希望 Angular 控制器然后去执行它自己的获取请求到服务器只是为了以不同的格式获取视图已经可用的相同参数。

回答by Matty J

You should pass it from your server side controller to your AngularJS controller by using either a 'value' or 'constant' provider, as described here: https://docs.angularjs.org/guide/providers

您应该使用“值”或“常量”提供程序将其从服务器端控制器传递到 AngularJS 控制器,如下所述:https: //docs.angularjs.org/guide/providers

For example, you could do something like the following:

例如,您可以执行以下操作:

<script>
    angular.module("hobbitModule").value("companionship", @Html.Raw(Model));
</script>

and then inject it in to your controller

然后将其注入您的控制器

var module = angular.module("hobbitModule");
module.controller("CompanionshipController", function($scope, companionship) {
    $scope.companions = companionship;
});

as described in this article: http://blog.mariusschulz.com/2014/03/25/bootstrapping-angularjs-applications-with-server-side-data-from-aspnet-mvc

如本文所述:http: //blog.mariusschulz.com/2014/03/25/bootstrapping-angularjs-applications-with-server-side-data-from-aspnet-mvc

If you think it may become more complicated that just a value, you could use a Service provider and inject that instead of the value provider.

如果您认为只有一个值可能会变得更复杂,您可以使用服务提供者并注入它而不是值提供者。

回答by Sirwan Afifi

supposed that you have this model :
Model

假设你有这个模型:
模型

public class Product
{
        public int Id { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
        public string Description { get; set; }
}

this way you can pass data from your controller into your view :
Controller

这样您就可以将数据从控制器传递到您的视图中:
Controller

public string GetSerializedProduct()
{
    var products = new[] 
    { 
        new Product{Id=1,Name="product1",Price=4500,Description="description of this product"},
        new Product{Id=2,Name="product2",Price=500,Description="description of this product"},
        new Product{Id=3,Name="product3",Price=400,Description="description of this product"},
        new Product{Id=4,Name="product4",Price=5500,Description="description of this product"},
        new Product{Id=5,Name="product5",Price=66500,Description="description of this product"}
    };
    var settings = new JsonSerializerSettings { ContractResolver=new CamelCasePropertyNamesContractResolver()};
    return JsonConvert.SerializeObject(products,Formatting.None,settings);
    }
}

View:

查看

@model string
<div class="container" ng-init="products = @Model">
    <div class="row">
        <div class="col-lg-12">
            <table class="table table-condensed table-hover">
                <tr>
                    <th>Id</th>
                    <th>Product Name</th>
                    <th>Price</th>
                    <th>Description</th>
                </tr>
                <tr ng-repeat="product in products">
                    <td>{{product.id}}</td>
                    <td>{{product.name}}</td>
                    <td>{{product.price}}</td>
                    <td>{{product.description}}</td>
                </tr>
            </table>
        </div>
    </div>
</div>