【问题标题】:Pass url from web.config to angularjs .html view [duplicate]将 url 从 web.config 传递到 angularjs .html 视图 [重复]
【发布时间】:2016-09-16 14:15:41
【问题描述】:

我在这个应用程序中使用带有 Angularjs 的 Asp.net MVC。如何将 web.config 中关键的 url 传递给 angularjs .html 视图中的链接?

Web.config:

<add key="SampleTemplate" value="C:\SampleTemplate" />

模板视图.html:

<a ng-href= "WHAT SHOULD I WRITE HERE?"> Edit Template</a>

【问题讨论】:

  • 使用$http 进行ajax 调用以从服务器获取配置密钥并将响应值分配给$scope 变量..

标签: angularjs model-view-controller web-config angular-controller


【解决方案1】:

您可以阅读服务器端代码中的配置部分并通过$http.get 检索它。这是最好的解决方案。

您应该在 MVC ApiController 中编写方法(也可以是 MVC Action)。比如:

[Route("settings/{key}")]
[HttpGet]
public HttpResponseMessage GetSetting(string key)
{
    try 
    {
        return Request.CreateResponse(HttpStatusCode.OK,
            System.Configuration.ConfigurationManager.AppSettings[key]);
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)
    }
}

在您的角度服务中:

app.service('utilsService', utilsService);

utilsServcie.$inject = ['$http'];
function utilsServcie($http){
    this.readServerProperty = function(key){
        $http.get('/api/v1/settings/' + key).then(
            function(response){
                return response.data;
            },
            function(error){
                alert(error.data.message);
            }
        );
    }
}

您可以在需要的地方使用此服务,如下所示:

app.controller('MainController', MainController);

MainController.$inject = ['utilsServcie'];
function MainController(utilsServcie){

    var vm = this;

    utilsServcie.readServerProperty('SampleTemplate').then(function(path){

        vm.path = path;

    });

}

在你看来:

<div ng-controller="MainController as mc">
    <a ng-href= "mc.path"> Edit Template</a>
</div>

嗯,这一切都是我凭记忆写的,所以可能会有一些小错误,但你可以理解这个想法。

这就是所有人。 :D

【讨论】:

  • 你能举个例子吗?
  • 在这里,检查更新。 :)
猜你喜欢
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多