Angular $Scope service: How does it work? - Printable Version +- 0Day Forums (https://0day.red) +-- Forum: Coding (https://0day.red/Forum-Coding) +--- Forum: FrameWork (https://0day.red/Forum-FrameWork) +--- Thread: Angular $Scope service: How does it work? (/Thread-Angular-Scope-service-How-does-it-work) |
Angular $Scope service: How does it work? - opisthocomeeylusblai - 07-20-2023 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; }]); RE: Angular $Scope service: How does it work? - geanticlinalfdqg - 07-20-2023 `$scope` isn't a service *per se*; it's just a child scope of the application's root scope. So you should check out the [$rootScope service][1] documentation. Technically speaking, a scope is an object that prototypically inherits from `$rootScope` and it's created using the `$new` method. Since it's an object, you can create new properties on it just by doing `$scope.property = value;`. No getter/setter methods under the hood. To understand it better you should look up `function $RootScopeProvider()` in Angular source code. And since the scope is just an object, you can access it in the `link` function within a directive the same way you do it in controllers. No magic required. :) About `$apply`, it's not a service either, but a method of the `$rootScope` service. All it does is trigger a digest cycle in order for Angular to process the watchers of the current scope and its children. Finally, you might be interested in checking out this post on [understanding Angular scopes][2], in case you haven't already. :) [1]: [To see links please register here] .$rootScope.Scope[2]: [To see links please register here] |