I'm fairly new to Javascript ( just finished the book Eloquent Javascript ), and am currently reading AngularJS from O'Reilly. And getting this small snippet of code to work from the book drove me crazy for hours and led me down rabbit holes thinking I messed up somewhere in setting up my environment. The only difference in the code provided by the AngularJS book and the code I typed up was that I left out the '$' in "$scope" in the TextController function. Putting the '$' back in allowed the code to work.
Here was my reasoning for initially leaving it out: Oh, '$scope' is just a variable name local to the function. Like any other programming language such as Java or C++, because this parameter is just a local variable, I can name it whatever I want since whatever argument gets passed into the function will just get passed by value.
Please correct my reasoning and explain why the name of the parameter has to be "$scope".
<!doctype html>
<html ng-app>
<body ng-controller="TextController">
<p>{{someText}}</p>
<script src="angular.min.js"></script>
<script>
function TextController($scope) {
$scope.someText = 'You have started your journey.';
}
</script>
</body>
</html>
$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive. It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.
Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component.
$scope bind value to the view and var is the local variable to the application.
This is handled by the Angular injector.
http://docs.angularjs.org/api/auto/service/$injector
In JavaScript calling toString() on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted. NOTE: This does not work with minification, and obfuscation tools since these tools change the argument names.
http://docs.angularjs.org/guide/di
Given a function the injector can infer the names of the service to inject by examining the function declaration and extracting the parameter names. In the above example $scope, and greeter are two services which need to be injected into the function.
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