在我的视图代码下方(javascript代码在视图中,只是用于测试的温度)。
我想将ASP.NET MVC模型(@Model
)分配给AngularJS范围($scope.person
)
我该怎么做?
谢谢,
视图
@model MyApp.Person
<script>
var myApp = angular.module('myApp', []);
myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
$scope.person = ?????
}]);
</script>
更新1: 我在JS文件中尝试了这段代码:
var myApp = angular.module('myApp', []);
myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
$scope.person = @Html.Raw(window.person);
}]);
在视图文件中:
<script>
@{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
}
window.person = serializer.Serialize(Model);
</script>
我收到2个错误:
ReferenceError: serializer is not defined (on windows)
window.person = serializer.Serialize(Model);
SyntaxError: illegal character (it's the @)
$scope.person = @Html.Raw(window.person);
答案 0 :(得分:3)
我不确定这是否适用于Angular。
您可以使用Json.Encode方法将数据对象转换为JavaScript Object Notation(JSON)格式的字符串。
window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable.
在您的角度代码使用中,
$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>
答案 1 :(得分:3)
<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>
答案 2 :(得分:0)
this.checked == true
并在你的(有角度的)控制器中:
<script>
myApp.value('person', @Html.Raw(Model));
</script>
如果您在控制器上“注入”了json值,则会对其进行排序。
答案 3 :(得分:0)
首先在全局java脚本变量中赋值,然后在单独的角度文件中使用它
<script>
var obj = '@Html.Raw(Model)';
</script>
现在在您的角度页面
$scope.person = obj;