I'm trying to keep my controllers as thin as possible, so I keep my domain logic in services and factories.
When I need to call a function in response to a user action like a click I assign the factory or service's function to the controller's $scope
variable.
$scope.saveStuff = myFactory.SaveStuff;
myFactory.SaveStuff
actually calls a bunch of private functions that $scope
can't see. I was a little surprised that a call to $scope.saveStuff
didn't result in a bunch of reference errors.
How does this work? Is $scope.saveStuff
just a function pointer to myFactory.SaveStuff
? Does this mean that $scope.saveStuff
is actually executing inside the scope of myFactory
so it has access to any private data/functions inside myFactory
?
Best Answer
Are you familiar with JavaScript closures? The function closes over the other functions so it retains memory of them when you call them in your controller or link function.
Consider this:
Here,
publicOne
callspublicTwo
, but_privateOne
is private topublicTwo
. Nonetheless, it gets called within the context ofpublicOne
because it closes over the_privateOne
function.