我正在学习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();
}
]);
我不明白我哪里出错了。
答案 0 :(得分: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>
答案 1 :(得分:0)
MVC查看渲染顺序 - 1.首先从 View 开始,然后是相关的bundle(外部CSS,JS)。
2.为了传递Model数据,我们需要在.cshtml文件中有一个内联元素(虽然不推荐),但是,如果这样就可以了,那么使用服务注入到相关的控制器 -
@section scripts
{
<script>
(function (undefined) {
window.app.factory('searchBinding', function () {
return @Html.Raw(Json.Encode(Model))
})
})(undefined);
</script>
}
现在,由于上面的代码是内联的,因此它将使用 View 本身执行,但Angular模块尚未定义为尚未下载。因此它会抛出 undefined 错误。
为了解决这个问题,我们可以在加载所有核心文件(包)之后在_Layout.cshtml中使用 RenderSection ,这甚至会强制内联部分仅在这些文件加载后加载已加载(在步骤2中。@section脚本用于此目的)。来自_Layout.cshtml文件的片段
@ Scripts.Render( “〜/捆绑/ angularjs”); @RenderSection( “脚本”,假);