Question

Just curious why whenever I see an example of a directive using a link, the parameter for scope is scope and not $scope?

This is always biting me because I'm so used to typing $scope, my brain auto-types it and I have to go back and correct it.

Was it helpful?

Solution

For link, scope is not injected using Angular's dependency injection. Controllers, etc use dependency injection that relies on matching the function argument var names with something to be injected.

link has an expected function signature that has explicit arguments:

function link(scope, element, attrs) { ... } 

Whereas when you use it in a controller, angular analyzes the controllers function args explicitely by name and determines exactly how to inject the scope in the same way that angular services are injected. In the context of dependency inject, objects with a prefix of $ are considered angular provided services.

Contrasting with dependency injections use of variable names, there's nothing stopping you from calling the link arguments whatever you want just like any other function. You could call it

function link(cat, banana, aardvark) { ... } 

and it would still work...

However with controllers etc a $scope with any other name is not as sweet

angular.module('foo')
  .controller('blah', function (scope) {
  // doesn't work
...
}
Licensed under: CC-BY-SA with attribution
scroll top