我正在學習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