Something that I was confused on here for a little while was what the difference between using $scope.myVariable or $scope.myFunction and using this.myVariable or this.myFunction. I hadn’t seen it clearly stated anywhere when and where to use which. I was accustomed to just using ‘this’ from the tutorials I was following on CodeSchool. This morning I was playing around with my web app and it finally donned on me what was going on, so here’s what I have so far.
Update: This might help as well
There is HELLUVA lot more going on with scopes than what I'm about to present here. I would AB-SO-LUTELY recommend checking out the AngularJS Docs for what's really going on behind the scenes. I'm literally just going to show the difference in how they're used.
In essence, $scope is like a container in which an application’s view can use data from the controller.
When using $scope, $scope must be passed into the controllers function as a parameter.
With the $scope now passed in, it can be used within the controller. This example uses $scope to create a function that will initiate a $http request which should return my IP address.
Then, comes the binding to the view. The ng-controller directive when using $scope doesn’t require adding an alias for the controller. Also, the directives don’t require the alias of the controller in order to reference a function in an ng-click or when an expression is displaying data.
The results will look like this:
Clicking ‘Get IP Address’ returns my correct IP address in to myIP, displays an alert with my IP address and successfully updates it on my page. The reason this works is because behind the scenes there is a $watch services associated with $scope which allows the view to be updated when the $scope’s myIP is updated.
Using ‘this’ instead of $scope
So now I’ll attempt to recreate the above using the this keyword instead. You’ll see at the end how the two aren’t exactly the same and how the outcome differentiates.
Here’s the controller again:
This time, the $scope isn’t passed in as a parameter to the function. The view now needs to be updated so that there’s an alias for the controller and the function and myIP variable must now be prefixed with the controller’s alias.
If we check out the resulting view it will look the same as before. But, when ‘Get IP Address’ is clicked this time. The Alert appears with the correct data, but the views representation of myIP isn’t updated. Which is due to the fact that there’s nothing ‘watching’ for the change, which $scope does naturally.
And as stated – the resulting controller.myIP isn’t updated after the request, so it still says ” What IP? ”