![](/img/trans.png)
[英]Post AngularJS model to complex model in ASP.NET MVC controller
[英]AngularJS + ASP.NET MVC - Controller undefined
大家好,我遇到了AngularJs的問題,無法重新調整控制器,下面總結了我所做的事情。
起點:AngularJs教程http://www.thinkster.io/angularjs/ZPCQtVfGba/angularjs-controllers
問題:在文件中定義了控制器(訪問頁面時可以正確檢索),將ng-controller指令添加到相關的div中,出現了JavaScript運行時錯誤(
錯誤:[ng:areq] http://errors.angularjs.org/1.3.0-beta.18/ng/areq?p0=FirstCtrl&p1=not%20a%20function%2C%20got%20undefined
)
發布之前,我檢查了是否在包含Angular之前已經包含了我的控制器實現,但事實並非如此。
我想念什么? 我懷疑這可能與在全局范圍內聲明控制器有關(例如, 控制器不是函數,在全局定義控制器時未定義 ),但是我不確定這是否確實如此。
_Layout .cshtml
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@RenderSection("PageSpecificStyles",required:false)
</head>
<body>
@RenderBody()
@RenderSection("BodyScripts", required: false)
</body>
</html>
Index.cshtml:
@{
ViewBag.Title = "Home Page";
}
@section PageSpecificStyles{
<style>
div {
margin-left: 20%;
}
</style>
}
@section BodyScripts{
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script>
<script src="~/Scripts/FirstCtrl.js"></script>
}
<div ng-controller="FirstCtrl">
<div>
<h1>Hello {{data.message}}</h1>
</div>
</div>
FirstCtrl.js(在〜/ scripts中)
function FirstCtrl($scope) {
$scope.data = { message: "Cat!" };
}
如您所懷疑的那樣,由於您使用的是Angular 1.3 Beta ,它對全局控制器構造函數的發現沒有隱式支持 ,因此您需要在模塊中注冊控制器。
angular.module('yourApp').controller('FirstCtrl',['$scope', FirstCtrl]);
並且由於您正在定義模塊,因此需要在ng-app中指定模塊名稱。
<html ng-app="yourApp">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.