Assigning an ASP.NET MVC Model to an AngularJS Area

Below is the code of my view (javascript code is in the view, just temp for testing).

I would like to assign the ASP.NET MVC ( @Model) model to the AngularJS ( $scope.person) scope

How can i do this?

Thank,

View

@model MyApp.Person

<script>
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = ?????
}]);
</script>

Update 1: I tried this code in a JS file:

var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = @Html.Raw(window.person);
}]);

In the view file:

<script>
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    }
    window.person = serializer.Serialize(Model);
</script>

I get 2 errors:

ReferenceError: serializer is not defined (on windows)
window.person = serializer.Serialize(Model);

SyntaxError: illegal character (it the @)
$scope.person = @Html.Raw(window.person);
+4
source share
4 answers
<script>
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var json = serializer.Serialize(Model);
    }
    var myApp = angular.module('myApp', []);

    myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
        $scope.person = @Html.Raw(json);
    }]);
</script>
+3
source

I'm not sure if this will work with Angular.

Json.Encode , JavaScript (JSON).

window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable.

angular

$scope.person = window.person

.

@model MyApp.Person

<script>
window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable.
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = window.person
}]);
</script>
+2

. . :

<script>
    myApp.value('person', @Html.Raw(Model));
</script>

(angular) :

myApp.controller('personController', ['$scope', '$http', 'person' function ($scope, $http, person) {
    console.log(person);
}]);

"" json , .

0

java script, angular

 <script>
   var obj =  '@Html.Raw(Model)';
</script>
Hide result

angular

$scope.person = obj;
Hide result
0

All Articles