【问题标题】:Passing information from Razor client (cshtml) to AngularJS将信息从 Razor 客户端 (cshtml) 传递到 AngularJS
【发布时间】:2014-08-22 03:13:24
【问题描述】:

我有以下剃须刀文件:

@{
    ViewBag.Title = "Blah";
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.InitModule = "myFooModule";
}

@section Scripts{
    <script src="~/Scripts/angular-route.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/js/recipes.js"></script>
}
<div data-ng-view

这是我的 angularjs 代码:

var testModule = angular.module("myFooModule", ['ngRoute']);

appetizerModule.config(["$routeProvider", function ($routeProvider) {
    $routeProvider.when("/", {
        controller: "myController",
        templateUrl: "/Templates/test.html"
    });
    $routeProvider.otherwise({ redirectTo: "/" });
}]);

我想将带有“myuserinfofromPage”等数据的变量从我的 razor 页面传递给我的 angularJs,以便我可以使用该数据(“myuserinfofromPage”)来执行某些操作集。由于我是 AngularJS 的新手,我正在努力寻找一种干净的方式来传递数据。将简单数据从 Razor(cshtml) 传递到我的 Angular 代码的最佳方式是什么?

【问题讨论】:

  • 在 Angular 中,您通常从异步 Web API 调用获取数据,该调用与您的主网页不同。我建议你设置一个 Web API 控制器。
  • 我做到了!但我想将一个参数从我的剃刀视图传递给我的 Angular 代码。我在我的角度控制器中调用我的 Web API,并希望为不同的视图重用相同的代码。对不起,如果它听起来比实际更复杂。
  • 未来考虑使用 ng-init 从标记中初始化作用域变量
  • 以后考虑给出代码示例

标签: javascript asp.net-mvc angularjs asp.net-mvc-4 razor


【解决方案1】:

您可以在剃须刀页面中嵌入以下内容:

 <script>
  app.value('myValue', @Html.Raw(Json.Encode(Model)))
 <script>

其中 Model 是您要呈现的 .NET 对象。

然后将其注入您的控制器:

 app.controller('ctrl', function($scope, myValue) 
 {
      //use myValue
 });

【讨论】:

  • 这非常有效。谢谢!正是我需要的!
  • 是_Layout还是View有关系吗?
【解决方案2】:

您可以将 json 格式的数据传递给您的视图,并在使用工厂引导数据后,即:

testModule.factory('UserService', function () {

      var _userInfo= @Html.Raw(ViewBag.UserDataInJsonFormat); //<- your data is going here

      return {
      userInfo : _userInfo

      }

}

【讨论】:

  • 感谢 pixelbits 和 sylwester 的回复。我使用角度指令来传递元素数据并将其存储在我的角度控制器中的 $scope 变量中。参考:fdietz.github.io/recipes-with-angular-js/directives/…
  • @sylwester 我收到了Unexpected token @ in JSON at position 0。还有什么需要补充的吗?
  • @stevek 看起来你的 json 无效
【解决方案3】:

感谢 pixelbits 和 sylwester 的回复。我使用角度指令来传递元素数据并将其存储在我的角度控制器中的 $scope 变量中。参考:http://fdietz.github.io/recipes-with-angular-js/directives/passing-configuration-params-using-html-attributes.html

<body ng-app="MyApp">
  <div my-widget="Hello World"></div>
</body>
var app = angular.module("MyApp", []);

app.directive("myWidget", function() {
  var linkFunction = function(scope, element, attributes) {
    scope.text = attributes["myWidget"];
  };

  return {
    restrict: "A",
    template: "<p></p>",
    link: linkFunction
  };
});

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2013-02-21
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多