AngularJS beginner: ng-controller not working

时间秒杀一切 提交于 2019-12-04 03:19:47

问题


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>

EDIT: 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: 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.


回答1:


If you're using angularjs 1.3+ versions then you can not declare global controller like above you're doing.

You should initialize like below.

<div ng-app="appname" ng-controller="MyFirstCtrl">
var app = angular.module('appname', []);
app.controller('MyFirstCtrl',function(){
   //controller code here
});



回答2:


I don't see how you are initialising the angularjs app, don't know if that is already included in the js file you have linked, but in principle, you should have something like this:

var app = angular.module("appName", []).controller("ControllerName", function ($scope){
  //your controller code here
});

And then have in your HTML code something like:

<html ng-app="appName">



回答3:


Add the controller to the angular application module

.module('LogIn')
.controller('LoginController', LoginController)



来源:https://stackoverflow.com/questions/31346238/angularjs-beginner-ng-controller-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!