gpt4 book ai didi

javascript - 使用工厂方法创建服务时,AngularJS 模块未定义

转载 作者:行者123 更新时间:2023-11-28 00:00:03 25 4
gpt4 key购买 nike

我正在 MVC 中学习 AngularJS,并创建了服务将我的模型传递给 Angular Controller 。但它给了我错误

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();
}
]);

我不明白我哪里出了问题。

最佳答案

您需要将内联脚本移到 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>

关于javascript - 使用工厂方法创建服务时,AngularJS 模块未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com