Montreal Montreal - 3 months ago 11
AngularJS Question

What does '$' really mean in '$scope' angular varialble

Why this code does work

<div ng-app="my_app" ng-controller="my_ctrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("my_app", []);

function ScopeController($scope) {
$scope.firstName = "John";
$scope.lastName = "Another John";
}
app.controller("my_ctrl", ScopeController);
</script>


And this doesn't

function ScopeController(scope) {
scope.firstName = "John";
scope.lastName = "Another John";
}


As far as I understand programming,
$scope
is just a local variable for
ScopeController
. And
ScopeController
itself is just a callback function. So why correct work of my code depends on how I name callback's local variable? If it's not just a local variable, then why it passed as an argument?

Answer

It doesn't mean anything. $scope is simply the name of the scope service. Angular prefixes most of its stuff with a $ in order to avoid stepping on names that you choose, so you won't have to prefix all your clashing names with $ or something else. It ceases to work when you simply call it scope, since Angular figures out which services it should inject based on the name of the paramter; and it doesn't know any service called scope. To make the variable name arbitrary, use the annotated syntax to define your controller:

function ScopeController(scope) { ... }

app.controller('my_ctrl', ['$scope', ScopeController]);