AngularJS初学者:NG-控制器不工作 [英] AngularJS beginner: ng-controller not working
问题描述
我只是试图让我的头周围AngularJS的基础知识。我试着写一个简单的MVC应用程序,但是控制器似乎并不奏效。该文件可以找到的角LIB只是觉得,我已经测试了通过排除'NG控制器。
I'm just trying to get my head around the basics of AngularJS. I tried writing a simple MVC app, but the controller doesn't seem to be working. The file can find the angular lib just find, I already tested that by excluding 'ng-controller'.
<!DOCTYPE html>
<html ng-app>
<head>
<script src='js/lib/angular.js'></script>
<script>
// controller
function MyFirstCtrl($scope) {
// model
var employees = ['Christopher Grant', 'Monica Grant', 'Christopher
Grant', 'Jennifer Grant'];
$scope.ourEmployees = employees;
}
</script>
</head>
<body ng-controller='MyFirstCtrl'>
<!-- view -->
<h2>Number of employees: {{ourEmployees.length}}</h2>
</body>
</html>
编辑:
错误日志说以下内容:
The error log says the following:
Uncaught SyntaxError: Unexpected token ILLEGAL , line 9
Uncaught SyntaxError: Unexpected token { , line 19
Error: [ng:areq] Argument 'MyFirstCtrl' is not a function, got undefined
EDIT2:我改变了code这样:
I changed the code to this:
<!DOCTYPE html>
<html ng-app='MVCExample'>
<head>
<script src='js/lib/angular.js'></script>
<script>
var app = angular.module('MVCExample', []);
// controller
app.controller("MyFirstCtrl", function($scope) {
// model
var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
$scope.ourEmployees = employees;
});
</script>
</head>
<body ng-controller='MyFirstCtrl'>
<!-- view -->
<h2>Number of employees: {{ourEmployees.length}}</h2>
</body>
</html>
这也证明了雇员数组,我是非法的,因为我有一个字符串项分成两行。上述作品。我使用的入门书一定是过时的,这是不幸的。
It also turned out that the 'employees' array that I had was illegal since I had one string entry split into two lines. The above works. The beginner book I am using must be outdated, which is unfortunate.
推荐答案
如果你使用angularjs 1.3 +
的版本,那么你不能声明全局控制器像上面你重新做。
If you're using angularjs 1.3+
versions then you can not declare global controller like above you're doing.
您应该初始化像下面。
<div ng-app="appname" ng-controller="MyFirstCtrl">
var app = angular.module('appname', []);
app.controller('MyFirstCtrl',function(){
//controller code here
});
这篇关于AngularJS初学者:NG-控制器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!