为什么我的NG控制器不能在我的代码中工作?

时间:2018-04-14 06:34:23

标签: angularjs

<!DOCTYPE html>
<html data-ng-app="myapp">
<head>
    <title>Using AngularJS Directives and Data Binding</title>
</head>
<body>
    <div data-ng-controller="SimpleController">
    Name:
    <br />
    <input type="text" data-ng-model="name" /> 
    <br />
    <ul>
        <li data-ng-repeat="cust in customers | filter:name ">{{ cust.name }} - {{ cust.city | uppercase }}</li>
    </ul>
    </div>

<script src="scripts/lib/angular.min.js"></script>
<script src="scripts/lib/angular-route.min.js"></script>
<script src="scripts/lib/angular-animate.min.js"></script>
<script src="scripts/lib/jquery.min.js"></script>


<script>
     var myapp = angular.module('myapp',[]); 
     angular.module('myapp').SimpleController('Ctrl', function($scope) { 
        $scope.customers = [
                            { name: 'Kobe Bryant', city: 'Philadelphia' }, 
                            { name: 'Magic Johnson', city: 'Lansing' },
                            { name: 'James Worthy', city: 'Gastonia' }
                        ];
    }
</script>

</body>
</html>

这只是出于学习目的,但我一直在努力弄清楚为什么我的NG控制器不能为我工作。我认为它是如何编写代码的.js部分的语法错误。

1 个答案:

答案 0 :(得分:1)

SimpleController应该是您的controller名称,而不是角度模块的function name

问题1:  改变

angular.module('myapp').SimpleController('Ctrl', function($scope)

<强> angular.module('myapp').controller('SimpleController', function($scope)

问题2:您遇到语法错误。 我将其修复为以下代码段和plunker

&#13;
&#13;
     var myapp = angular.module('myapp',[]); 
     angular.module('myapp').controller('SimpleController', function($scope) { 
        $scope.customers = [
                            { name: 'Kobe Bryant', city: 'Philadelphia' }, 
                            { name: 'Magic Johnson', city: 'Lansing' },
                            { name: 'James Worthy', city: 'Gastonia' }
                        ];
    })
&#13;
<!DOCTYPE html>
<html data-ng-app="myapp">
<head>
    <title>Using AngularJS Directives and Data Binding</title>
</head>
<body>
    <div data-ng-controller="SimpleController">
    Name:
    <br />
    <input type="text" data-ng-model="name" /> 
    <br />
    <ul>
        <li data-ng-repeat="cust in customers | filter:name ">{{ cust.name }} - {{ cust.city | uppercase }}</li>
    </ul>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>



</body>
</html>
&#13;
&#13;
&#13;

请运行以上代码段

Here is a working DEMO