I'm brand new to AngularJS and I've encountered a bit of confusion with the documentation code. Even though the global function controller is working fine for me, the official docs suggest creating the controller through the Angular module instead.
Click here to view a JSFiddle containing the same code.
Functioning JS Controller:
function MyController($scope) {
$scope.username = 'World';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
}
Malfunctioning JS Controller:
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.sayHello = function() {
$scope.greeting = "Hi " + $scope.username;
};
}]);
HTML File:
<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>