AngualrJS控制器无法正常工作

时间:2015-05-10 09:49:29

标签: javascript angularjs

我刚开始按照this youtube video学习AngularJS。第一部分没问题,除了涉及controller部分。

我的代码如下(与视频中的相同)

<html data-ng-app="">

    <head>
        <script src="angular.min.js"></script>
        <script>
            function SimpleController($scope) {
                $scope.customers = [{
                    name: 'Kamal',
                    city: 'York'
                }, {
                    name: 'Sunil',
                    city: 'DC'
                }, {
                    name: 'Malith',
                    city: 'Gotham'
                }];
            }
        </script>
    </head>

    <body>
        <div data-ng-controller="SimpleController">Name :
            <input type="text" data-ng-model="name" />
            </br>
            <ul>
                <li data-ng-repeat="cust in customers | filter :name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
            </ul>
        </div>
    </body>

</html>

当我添加data-ng-controller="SimpleController"时,它将无效并在控制台中出现以下错误。

enter image description here enter image description here

然后,当我尝试在SO中发布问题时,I tried it in JSfiddle。我添加了Angular.js并选择了onLoad而没有工作。但是,当我选择no wrap - in <head> 时,它可以正常运行

但我不能在我的本地机器上这样做,所以问题仍然存在。

有人能指出我正确的道路吗?

2 个答案:

答案 0 :(得分:3)

您需要初始化应用:

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

<div ng-app="myApp" ng-controller="SimpleController">
<!--         ^^^^^ -->

演示:http://jsfiddle.net/xy23ybzp/2/

文档:https://docs.angularjs.org/guide/bootstrap

检查文档中的手动初始化部分

答案 1 :(得分:0)

在获得此问题所列答案的帮助后。我搞定了。以下是工作代码。

<html  >
<head>
<script src = "angular.min.js"  ></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("SimpleController",function($scope){
        $scope.customers = [
        {name :'Kamal',city : 'York'},
        {name : 'Sunil',city:'DC'},
        {name : 'Malith',city:'Gotham'}
        ];
    }); 
</script>

  </head>
  <body  >

  <div ng-app="myApp"  data-ng-controller="SimpleController">
    Name : 
    <input type="text" data-ng-model="name" />
    </br>
    <ul>
        <li data-ng-repeat="cust in customers | filter :name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
    </ul>
</div>

</body>
</html>