问题描述
我正在MVC中学习AngularJS,并创建了将模型传递给Angular Controller的服务。 但这给我错误
JavaScript运行时错误:“ accountModule”未定义
这就是我在做什么:
AccountController.cs
public ViewResult Index()
{
var accounts = new List<Accounts>
{
new Accounts
{
Id = 111,
Designation = "Tech Lead",
Name = "AAA"
},
new Accounts
{
Id = 222,
Designation = "Softwre Engineer",
Name = "BBB"
},
new Accounts
{
Id = 111,
Designation = "Project Manager",
Name = "CCC"
}
};
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var accountJson = JsonConvert.SerializeObject(accounts, Formatting.None, settings);
return this.View("Index", (object)accountJson);
}
Index.cshtml
<script type="text/javascript" src="../../Scripts/Modules/Account/Account.js"></script>
<div ng-app="accountModule">
<div ng-controller="accountController">
<h1>{{message}}</h1>
<div class="container" ng-init="employees in {{employees}}">
<h2>Employee Details</h2>
<div class="row">
<table class="table table-condensed table-hover">
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Designation
</td>
</tr>
<tr ng-repeat="emp in employees">
<td>
{{emp.id}}
</td>
<td>
{{emp.name}}
</td>
<td>
{{emp.designation}}
</td>
</tr>
</table>
</div>
</div>
<div>
@*{{emps}}*@
</div>
</div>
</div>
<script type="text/javascript">
accountModule.factory('accountService', function() {
var factory = {};
factory.employees = @Html.Raw(Model);
return factory;
});
</script>
Account.js
var account = angular.module('accountModule',[]);
account.controller('accountController', [
'$scope', 'accountService', function ($scope, accountService) {
$scope.employees = accountService.employees;
$scope.message = "Hi on " + (new Date()).toDateString();
}
]);
我不明白我要去哪里错了。
1楼
您需要将内联脚本移到account.js之后。
另外变量应该是account
而不是accountModule
码
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="account.js"></script>
<script type="text/javascript">
//account.factory('accountService', function() { //this is alternative use below one
angular.module('accountModule').factory('accountService', function() {
var factory = {};
factory.employees = @Html.Raw(Model);
return factory;
});
</script>
2楼
MVC View渲染顺序-1.首先从View开始,然后从相关的包(外部CSS,JS)开始。
2.为了传递模型数据,我们需要在.cshtml文件中有一个内联元素(尽管不建议这样做),但是,如果这样做,可以使用服务注入到相关的控制器-
@section scripts
{
<script>
(function (undefined) {
window.app.factory('searchBinding', function () {
return @Html.Raw(Json.Encode(Model))
})
})(undefined);
</script>
}
现在,由于上面的代码是内联的,因此可以使用View本身执行它,但是Angular模块尚未定义为尚未下载。 因此,它将引发未定义的错误。
为了解决这个问题,我们可以在所有核心文件(捆绑包)加载后在_Layout.cshtml中使用RenderSection ,这甚至迫使内联节也仅在这些文件加载??后才加载(在步骤2中。@section脚本用于)。_Layout.cshtml文件中的代码段
@ Scripts.Render( “?/捆绑/ angularjs”); @RenderSection( “脚本”,假);