Angular controller, services, scopes fundamental concept

Controller:

Use controllers to:

  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Do not use controllers to:

  • Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
  • Format input — Use angular form controls instead.
  • Filter output — Use angular filters instead.
  • Share code or state across controllers — Use angular services instead.
  • Manage the life-cycle of other components (for example, to create service instances).
Setting up the initial state of a $scope object:
     init the $scope.
Adding Behavior to a Scope Object:
     add function to the $scope.

Using Controllers Correctly
In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.


Services:
Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Registering a Service with $provide

You can also register services via the $provide service inside of a module's config function:

angular.module('myModule', []).config(['$provide', function($provide) {
  $provide.factory('serviceId', function() {
    var shinyNewServiceInstance;
    // factory function body that constructs shinyNewServiceInstance
    return shinyNewServiceInstance;
  });
}]);

This technique is often used in unit tests to mock out a service's dependencies.


Scopes:
Each Angular application has exactly one root scope, but may have several child scopes.
prototypical inheritance


Scope Events Propagation

Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.

Scope life cycle:
When the browser calls into JavaScript the code executes outside the Angular execution context, which means that Angular is unaware of model modifications. 

Controllers and Scopes

Scopes and controllers interact with each other in the following situations:

  • Controllers use scopes to expose controller methods to templates (see ng-controller).

  • Controllers define methods (behavior) that can mutate the model (properties on the scope).

  • Controllers may register watches on the model. These watches execute immediately after the controller behavior executes.

Integration with the browser event loop

The diagram and the example below describe how Angular interacts with the browser's event loop.

  1. The browser's event-loop waits for an event to arrive. An event is a user interaction, timer event, or network event (response from a server).
  2. The event's callback gets executed. This enters the JavaScript context. The callback can modify the DOM structure.
  3. Once the callback executes, the browser leaves the JavaScript context and re-renders the view based on DOM changes.

Angular modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and Angular execution context. Only operations which are applied in the Angular execution context will benefit from Angular data-binding, exception handling, property watching, etc... You can also use $apply() to enter the Angular execution context from JavaScript. Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event. An explicit call to $apply is needed only when implementing custom event callbacks, or when working with third-party library callbacks.

  1. Enter the Angular execution context by calling scope.$apply(stimulusFn), where stimulusFn is the work you wish to do in the Angular execution context.
  2. Angular executes the stimulusFn(), which typically modifies application state.
  3. Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The$digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes.
  4. The $evalAsync queue is used to schedule work which needs to occur outside of current stack frame, but before the browser's view render. This is usually done with setTimeout(0), but the setTimeout(0) approach suffers from slowness and may cause view flickering since the browser renders the view after each event.
  5. The $watch list is a set of expressions which may have changed since last iteration. If a change is detected then the $watch function is called which typically updates the DOM with the new value.
  6. Once the Angular $digest loop finishes the execution leaves the Angular and JavaScript context. This is followed by the browser re-rendering the DOM to reflect any changes.

Here is the explanation of how the Hello world example achieves the data-binding effect when the user enters text into the text field.

  1. During the compilation phase:
    1. the ng-model and input directive set up a keydown listener on the <input> control.
    2. the interpolation sets up a $watch to be notified of name changes.
  2. During the runtime phase:
    1. Pressing an 'X' key causes the browser to emit a keydown event on the input control.
    2. The input directive captures the change to the input's value and calls $apply("name = 'X';") to update the application model inside the Angular execution context.
    3. Angular applies the name = 'X'; to the model.
    4. The $digest loop begins
    5. The $watch list detects a change on the name property and notifies the interpolation, which in turn updates the DOM.
    6. Angular exits the execution context, which in turn exits the keydown event and with it the JavaScript execution context.
    7. The browser re-renders the view with update text.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值