Reputation: 7458
I am trying to understand the $scope and how controller and view are clued together. When Angular first runs through the DOM elements, when it finds ng-controller what does it do? I know when it finds the binding variables, it creates either watch or keydown events and also for the events it injects itself and watch for the other related events. It is done by creating a scope for that given DOM element. so when an item changes in view or model it can push the value to proper places. My question is when does controller is instantiated and $scope get injected into it and how $scope calls associated methods when a event happens? Thanks
Upvotes: 0
Views: 57
Reputation: 5891
You would have to go through the documentation on their site for clarity. From what I understand when the framework encounters the ng-controller attribute on the view, it will attach and instantiate the controller. Any code directly within the controller function will run right there. If you want code to run only on certain events like a click event then you put ng-click='myFunction()'
on the element and myFunction
as a $scope property. If you want to run code inside a controller on some other event then you need to use $scope.$on
within the controller and $scope.$broadcast
to trigger the event outside. Note that controller should only have business logic. Any code to directly manipulate DOM goes within a Directive. Use scope
property in the directive to bind variables and functions between the controller and the directive.
Again, as I said, it will help to go through documentation and videos on youtube to get a better understanding on the foundations of AngularJS.
Upvotes: 2