angular.js

主要概念

angular.Module

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.

angular.module

The angular.module is a global place for creating, registering and retrieving Angular modules.

//定义方法在 angular.js/src/loader.js 文件中,在 AngularPublic.js 中调用
function setupModuleLoader(window) {
  // 参数个数决定行为
  function ensure(obj, name, factory) {
    return obj[name] || (obj[name] = factory());
  }
  // 占位 window.angular
  var angular = ensure(window, 'angular', Object);

  return ensure(angular, 'module', function() {
    return function module(name, requires, configFn) {

    });
  });
}
/** @type {angular.Module} */
var moduleInstance = {
  // Private state
  _invokeQueue: invokeQueue,
  _configBlocks: configBlocks,
  _runBlocks: runBlocks,

  // property
  requires: requires,
  name: name,

  //method
  provider: invokeLater('$provide', 'provider'),
  //... 省略,详见 https://docs.angularjs.org/api/ng/type/angular.Module
}

(待整理)

启动流程

一个最简单的使用 angular 的页面


<!doctype html>
<html lang="en" ng:app>
<head>
  <meta charset="utf-8">
  <title>Angular</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
</head>
<body>
  <p ng:init="a=1; b=2;">
    {{a}}
  </p>
</body>
</html>

先看打包后的完整文件 angular.js 的最后几行

  //try to bind to jquery now so that one can write jqLite(document).ready()
  //but we will rebind on bootstrap again.
  bindJQuery();

  publishExternalAPI(angular);

  jqLite(document).ready(function() {
    // 从这里载入 ng-app 指定的 module
    angularInit(document, bootstrap);
  });

再看看 angularInit 这个函数

function angularInit(element, bootstrap) {
  var appElement,
      module,
      config = {};

  // 此处代码省略 ...
  // 就是在页面中寻找 ngApp 这个 directive 来初始化 appElement 和 module 变量

  if (appElement) {
    config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
    // 启动 angular 应用
    bootstrap(appElement, module ? [module] : [], config);
  }
}

bootstrap 这个函数比较难,因为涉及到 angular 最核心的两个概念 $provide 和 $injector,下面容我娓娓道来

你可能感兴趣的:(angular.js)