我正在学习MVC中的AngularJS并创建了将模型传递给Angular Controller的服务。但它给我的错误使用工厂方法创建服务时AngularJS模块未定义
JavaScript runtime error: 'accountModule' is undefined
这是我在做什么:
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();
}
]);
我不明白我出错的地方。
您的最后一行'此外变量应该是帐户,而不是accountModule'解决了我的问题。谢谢您的帮助。现在我可以将Model传递给AngularJS控制器。 :) – user2988458
另外我想提一提的是,将服务移动到JS将不起作用,因为我必须将数据从'cshtml'传递到控制器。 – user2988458