浏览器无法解析AngularJS代码

Browser not able to parse AngularJS code

本文关键字:AngularJS 代码 浏览器      更新时间:2023-09-26

我在AngularJS中编写了一个简单的程序,在脚本标签中包含了缩小的angular JS,但浏览器无法解析angular JS代码。我有其他程序或多或少相同的代码,他们工作得很好。

我错过/忽略了什么吗?

MVC示例

<!DOCTYPE html>
<html ng-app>
    <head>
        <title>MVC Example</title>
        <script src="js/angular.min.js"></script>
        <script>
            function MyFirstCtrl($scope) {
                var employees = ['Catherine Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
                $scope.ourEmployees = employees;
            }
        </script>
    </head>
        <body ng-controller='MyFirstCtrl'>
        <h2>Number of Employees: {{ourEmployees.length}}</h2>
    </body>
</html>
浏览器输出:

Number of Employees: {{ourEmployees.length}}

您需要创建一个与ng-app一起使用的模块。

angular.module("foo", []);
angular.controller("MyFirstCtrl", MyFirstCtrl);
<html ng-app=foo>

你需要启动应用并以正确的形式添加控制器:

<script>
var app = angular.module("app", []);
app.controller('MyFirstCtrl', ['$scope', function ($scope) {
    var employees = ['Catherine Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
    $scope.ourEmployees = employees;
}]);
<script>

经过一番研究,我终于找到了v1.2和v1.3+的解决方案

v1.2

<!DOCTYPE html>
<html ng-app=foo>
    <head>
        <title>MVC Example</title>
        <script src="js/angular.min-1.2.js"></script>
        <script>
            angular.module("foo", []);
            angular.controller("MyFirstCtrl", MyFirstCtrl);
            var employees = ['Catherine Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
            function MyFirstCtrl($scope) {
                var employees = ['Catherine Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
                $scope.ourEmployees = employees;
            }
        </script>
    </head>
        <body ng-controller='MyFirstCtrl'>
        <h2>Number of Employees: {{ourEmployees.length}}</h2>
    </body>
</html>

v1.3 +起

<!DOCTYPE html>
<html ng-app=foo>
    <head>
        <title>MVC Example</title>
        <script src="js/angular.min-1.4.js"></script>
        <script>
            var employees = ['Catherine Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
            var foo = angular.module("foo", []);
            foo.controller("MyFirstCtrl", function ($scope) {
                $scope.ourEmployees = employees;
            });
        </script>
    </head>
        <body ng-controller='MyFirstCtrl'>
        <h2>Number of Employees: {{ourEmployees.length}}</h2>
    </body>
</html>