[英]AngularJS + ASP.NET MVC - Controller undefined
Hullo everyone, I am having a problem with AngularJs not reconizing my controller, I have summarised what I have done below. 大家好,我遇到了AngularJs的问题,无法重新调整控制器,下面总结了我所做的事情。
Starting point: AngularJs tutorial http://www.thinkster.io/angularjs/ZPCQtVfGba/angularjs-controllers 起点:AngularJs教程http://www.thinkster.io/angularjs/ZPCQtVfGba/angularjs-controllers
Problem: defined controller in file (gets retrieved correctly when visiting page), added ng-controller directive to relevant div, got javascript runtime error ( 问题:在文件中定义了控制器(访问页面时可以正确检索),将ng-controller指令添加到相关的div中,出现了JavaScript运行时错误(
Error: [ng:areq] http://errors.angularjs.org/1.3.0-beta.18/ng/areq?p0=FirstCtrl&p1=not%20a%20function%2C%20got%20undefined 错误:[ng:areq] http://errors.angularjs.org/1.3.0-beta.18/ng/areq?p0=FirstCtrl&p1=not%20a%20function%2C%20got%20undefined
) )
Before posting I checked whether I had included my controller implementation before including Angular but it is not the case. 发布之前,我检查了是否在包含Angular之前已经包含了我的控制器实现,但事实并非如此。
What am I missing? 我想念什么? I suspect it might have something to do with declaring controllers in the global scope (eg Controller not a function, got undefined, while defining controllers globally ) but I am not really sure whether this is indeed the case.
我怀疑这可能与在全局范围内声明控制器有关(例如, 控制器不是函数,在全局定义控制器时未定义 ),但是我不确定这是否确实如此。
_Layout .cshtml _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: 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 (in ~/scripts) FirstCtrl.js(在〜/ scripts中)
function FirstCtrl($scope) {
$scope.data = { message: "Cat!" };
}
As you suspected, since you are using angular 1.3 beta which has no implicit support for Global controller constructor function discovery , you need to register your controller with the module. 如您所怀疑的那样,由于您使用的是Angular 1.3 Beta ,它对全局控制器构造函数的发现没有隐式支持 ,因此您需要在模块中注册控制器。
angular.module('yourApp').controller('FirstCtrl',['$scope', FirstCtrl]);
and also since you are defining an module you need to specify the module name in your ng-app. 并且由于您正在定义模块,因此需要在ng-app中指定模块名称。
<html ng-app="yourApp">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.