I have the following code:
<!doctype html>
<html>
<body>
<div ng-controller="MyController">
Hello {{greetMe}}!
</div>
<script src="http://code.angularjs.org/snapshot/angular.js"></script>
<script>
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
</script>
</body>
</html>
from the website: https://docs.angularjs.org/guide/bootstrap
I really can't understand how the syntax is working, particularly,
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
What does the above ugly syntax mean? What is the role of 'MyController'? what does the array parameter mean? what does $scope mean? Who is calling the "function($scope)"?
How does it work? angular.bootstrap(document, ['myApp']);
When is the parameter above ['myApp'] injected and how?
The website doesn't explain anything regarding the syntax. Just assumed the reader knows all about it.
Please help.
Angular's dependency injection "stringifies" the function and then extracts the parameter names from the string, and uses that to find the dependant service.
However when you minify your code, those parameters because "g", "e", etc. Since Angular now can't know what service you actually wanted, they provide two different methods of explicitly describing your dependencies.
The first is to supply your function/class as the last parameter in an array, with the elements in the array before it being the original names of the parameters.
The alternative is to pass your original function/class, but to assign a "static" $inject property to the function itself. The property is given the value of an array of strings representing your original parameter names.
And, finally, the first parameter supplied to angular.controller/service/factory/etc is the name that you will be applying to the service you are registering. It is that string that other services will use to declare their dependency on your controller/service.
"myApp", in your sample, is a module. Modules aren't injected as dependencies but are instead a way of packaging up a group of services (controllers, directives). You can't inject a service from a different module without first declaring a dependency on that module by adding the name of the module to the array passed as the second parameter to angular.module. angular.bootstrap allows a module (and it's dependants) to work with a dom node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With