为什么我的简单angularjs不起作用?

时间:2014-09-08 15:19:11

标签: javascript angularjs

我有一个简单的angularjs测试实例。它使用全局但警报标签未运行。这是codechool的第一个例子。

为什么不运行?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
</head>
<body ng-controller="StoreController">


    <script type="text/javascript">
        function StoreController() {

            alert("hello");
        }

    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:9)

您缺少ng-app属性:

<html ng-app xmlns="http://www.w3.org/1999/xhtml">

另外,正如@PSL在评论中指出的那样,全局控制器无法从角度1.3开始工作。您应该定义与您的应用程序绑定的控制器。

将您的申请命名为ng-app,例如html代码:

<html ng-app="myapp" xmlns="http://www.w3.org/1999/xhtml">

然后,在javascript中,定义您的模块和控制器:

var myapp = angular.module("myapp", []);

myapp.controller('StoreController', ['$scope', 
    function ($scope) {
        alert("hello");
    }
]);

答案 1 :(得分:1)

您忘记添加ng-app行来引导您的应用。试一试:

<body ng-app="app">
    <div ng-controller="StoreController">Hello World</div>
    <script type="text/javascript">
        /* You forgot this line */
        angular.module("app", []);
        angular.module("app").controller("StoreController", [
            function() {
                alert("Hello");
            }
        ]);    

        /* Global controllers will not work with Angular 1.3 
        function StoreController() {

            alert("hello");
        }*/
    </script>
</body>
相关问题