Saturday, 17 August 2013

Angular $Scope service: How does it work?

Angular $Scope service: How does it work?

I've been experimenting with Angular for a couple of weeks and am a little
bothered that I don't understand the magic employed by the $scope service.
I've been successful in writing controllers that use the $scope service to
update models/views and I've been able to write my own directives to do
the same.
It's amazing! I just don't get what is going on under the hood with the
$scope service. When I create something like the following, what is
actually happening when I make the assignment to $scope.newproperty? I've
not been able to find any documentation specific to the $scope service.
module.controller("menu_ctrl",['$scope','$http',function($scope,$http){
$scope.newproperty = "Bound to model!" //magic!
}]);
Furthermore, when I create a new link function within a directive (example
below), how is it that all of a sudden I can just access the scope with a
variable? I assume there's some magic going on employing the $scope or
$apply services, but I'm just left guessing. Any help here would be much
appreciated. Thanks!
srvcs.directive('directiv', ['$http',function($http) {
var returnObj = {
link: function linkfn(scopeVar, instance, attr){
console.log(scopeVar);
scopeVar.newproperty = "Also bound to model!" //more magic!
...
...
}
};
return returnObj;
}]);

No comments:

Post a Comment