设置AngularJS $提供的最好方法是什么?c# MVC模型中的常量值



我有一个带有。net MVC/WebAPI后端的AngularJS应用程序。我有一个MVC操作,它提供加载AngularJS应用程序的主HTML页面。这个MVC操作从Web加载几个应用程序设置。配置以及数据库,并将它们作为模型返回给视图。我正在寻找一个好方法来设置这些MVC Model值作为$provide.constant值在我的AngularJS .config方法。

MVC控制器方法:

public ActionResult Index() {
    var model = new IndexViewModel {
        Uri1 = GetUri1(),
        Uri2 = GetUri2()
        //...etc
    };
    return View(model);
}

My MVC _Layout.cshtml:

@model IndexViewModel
<!doctype html>
<html data-ng-app='myApp'>
<head>
    @Styles.Render("~/content/css")
    <script type='text/javascript'>
        @if (Model != null)    //May be null on error page
        {
            <text>
                var modelExists = true;
                var uri1 = '@Model.Uri1';
                var uri2 = '@Model.Uri2';
            </text>
        }
        else
        {
            <text>
                var modelExists = false;
            </text>
        }
    </script>
</head>
<body>
    <!-- Body omitted -->
    @Scripts.Render("~/bundles/angular", "~/bundles/app") //Loads angular library and my application
</body>

app.js:

"use strict";
angular.module('myApp', [])
    .config(['$provide' '$window', function ($provide, $window) {
        if ($window.modelExists){
            $provide.constant('const_Uri1', $window.uri1);
            $provide.constant('const_URi2', $window.uri2);
        }            
    }]);

这是我的代码的一个非常简化的版本,但我认为它说明了我的问题。有没有更好或标准的方法来做这件事,我忽略了?我不喜欢我的_Layout.cshtml中的代码,因为我有更多的配置值。

如果你有一堆配置值,你不介意额外的网络调用,一种方法是创建一个MVC视图,将这些设置作为Angular常量返回…

using System.Web.Script.Serialization;
// ...
public ActionResult Settings(string angularModuleName = "myApp")
{
    var settings = new 
    {
        uri1 = GetUri1(),
        uri2 = GetUri1()
        // ...
    };
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(settings);
    var settingsVm = new SettingsViewModel
    {
        SettingsJson = json,
        AngularModuleName = angularModuleName
    };
    Response.ContentType = "text/javascript";
    return View(settingsVm);
}

在Razor视图中…

@model MyApp.SettingsViewModel
@{
    Layout = null;
}
(function (app) {
    app.constant('settings', @Html.Raw(Model.SettingsJson));
})(angular.module('@Model.AngularModuleName'));

在需要文件的页面中,只需添加一个script标签来引入常量…

@Scripts.Render("~/bundles/angular", "~/bundles/app") //Loads angular library and my application
<script src="/home/settings?appname=foo"></scripts>

这将返回脚本…

(function (app) {
    app.constant('settings', {
        "uri1": "https://uri1",
        "uri2": "https://uri2"
    });
})(angular.module('foo'));
现在你可以在Angular代码的任何地方注入settings服务了。没有任何东西泄露到全局作用域中。

您也可以使用这种技术将设置直接注入到特定的HTML视图中,但我通常更喜欢将其分开,以便仅在需要时包含它。

最新更新