我是 AngularJS 的新手,我试图弄清楚为什么某些文档代码对我不起作用。虽然下面的全局函数控制器对我有用,但文档说我应该通过 Angular 模块创建控制器。
工作 JS 控制器:
function MyController($scope) {
$scope.username = 'World';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
}
损坏的 JS 控制器:
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.sayHello = function() {
$scope.greeting = "Hi " + $scope.username;
};
}]);
HTML 文件:
<div ng-app="">
<div ng-controller = "MyController">
Your name:
<input type="text" ng-model="username">
<button ng-click='sayHello()'>greet</button>
<hr>
{{greeting}}
</div>
</div>