Montreal Montreal - 1 year ago 48
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>
Full Name: {{ firstName + " " + lastName }}

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

function ScopeController($scope) {
$scope.firstName = "John";
$scope.lastName = "Another John";
app.controller("my_ctrl", ScopeController);

And this doesn't

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

As far as I understand programming,
is just a local variable for
. And
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 Source

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]);