Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing information from Razor client (cshtml) to AngularJS

I have the following razor file:

@{
    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

Here is my angularjs code:

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

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

I would like to pass a variable with data like "myuserinfofromPage" from my razor page to my angularJs so that I can use that data ("myuserinfofromPage") to perform certain set of operations. I am struggling to get a clean way to pass data as I am new to AngularJS. What's the best way to pass simple data from Razor(cshtml) to my Angular code?

like image 211
user3794178 Avatar asked Jul 01 '14 14:07

user3794178


2 Answers

You could embed the following in your razor page:

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

Where Model is a .NET object you want to render.

Then inject it into your controller:

 app.controller('ctrl', function($scope, myValue) 
 {
      //use myValue
 });
like image 91
pixelbits Avatar answered Oct 12 '22 10:10

pixelbits


You can pass data in json format to you view and after bootstrap your data using factory ie:

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

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

      return {
      userInfo : _userInfo

      }

}

like image 39
sylwester Avatar answered Oct 12 '22 12:10

sylwester