我正在遵循教程:AngularJS in 60 min并且我无法使用一个简单的脚本,其中控制器在与视图相同的页面上声明(实际上它非常基本)。 但实际上它无法正常工作:
所以我的代码是:
<!DOCTYPE html>
<html data-ng-app="">
<head>
<title>AngularJS in 60 minutes</title>
<script src="./js/angular.min.js" charset="utf-8"></script>
</head>
<body>
<div class="container" data-ng-controller="SimpleController">
<h3>Instance of model and data binding</h3>
Name : <input type="text" data-ng-model="city"> {{ city }}
<h3>Instance of repeat directives</h3>
<ul>
<ol data-ng-repeat="person in people | filter:city | orderBy:'city'">{{ person.firstname}} {{ person.name | uppercase}} : {{ person.city}}</ol>
</ul>
</div>
<script>
function SimpleController($scope) {
$scope.people = [{firstname:'Valerie', name:'lion', city:'Paris'}, {firstname:'Fred', name:'creche', city:'Marly'}, {firstname:'Laurent', name:'larher', city:'Massy'}];
}
</script>
</body>
,结果在附图中。
欢迎任何建议。
佛瑞德
答案 0 :(得分:4)
我怀疑您使用的是Angular 1.3或更高版本。从1.3开始,Angular不再在window
上查找控制器。这是迁移链接:
https://docs.angularjs.org/guide/migration
相反,您应该使用app.controller()
语法:
var myApp = angular.module('myApp',[]);
myApp.controller('SimpleController',function($scope) {
$scope.people = [{firstname:'Valerie', name:'lion', city:'Paris'}, {firstname:'Fred', name:'creche', city:'Marly'}, {firstname:'Laurent', name:'larher', city:'Massy'}];
});
并更改你的HTML:
<html data-ng-app="myApp">
答案 1 :(得分:2)
在您的脚本中,您必须定义角度模块,然后定义控制器:
angular.module('myApp', []).controller('SimpleController', ['$scope', function($scope) {
// to do something....
}])
并在您的HTML中:
<html data-ng-app="myApp">
....
</html>
答案 2 :(得分:2)
从1.3开始,您无法将控制器定义为全局函数。您必须在模块上注册。为此,您必须拥有一个命名模块(data-ng-app='app'
)。然后,你就可以写
angular.module('app', []).controller("SimpleController", function($scope) { ...