依賴注入(DI)的好處不再贅言,使用過spring框架的都知道。angularjs作為前臺js框架,也提供了對DI的支持,這是javascript/jquery不具備的特性。angularjs中與DI相關有angular.module()、angular.injector()、 $injector、$provide。對于一個DI容器來說,必須具備3個要素:服務的注冊、依賴關系的聲明、對象的獲取。比如spring中,服務的注冊是通過xml配置文件的<bean>標簽或是注解@Repository、@Service、@Controller、@Component實現的;對象的獲取可以ApplicationContext.getBean()實現;依賴關系的聲明,即可以在xml文件中配置,也可以使用@Resource等注解在java代碼中聲明。在angular中,module和$provide相當于是服務的注冊;injector用來獲取對象(angular會自動完成依賴的注入);依賴關系的聲明在angular中有3種方式。下面從這3個方面,介紹下angular的DI。
1、angular.module()創建、獲取、注冊angular中的模塊
The angular.module() is a global place for creating, registering and retrieving Angular modules.When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved。
// 傳遞參數不止一個,代表新建模塊;空數組代表該模塊不依賴其他模塊var createModule = angular.module("myModule", []);// 只有一個參數(模塊名),代表獲取模塊// 如果模塊不存在,angular框架會拋異常var getModule = angular.module("myModule");// true,都是同一個模塊alert(createModule == getModule);該函數既可以創建新的模塊,也可以獲取已有模塊,是創建還是獲取,通過參數的個數來區分。
angular.module(name, [requires], [configFn]);
name:字符串類型,代表模塊的名稱;
requires:字符串的數組,代表該模塊依賴的其他模塊列表,如果不依賴其他模塊,用空數組即可;
configFn:用來對該模塊進行一些配置。
現在我們知道如何創建、獲取模塊了,那么模塊究竟是什么呢?官方的Developer Guide上只有一句話:You can think of a module as a container for the different parts of your app 主站蜘蛛池模板: 蒙城县| 靖宇县| 社旗县| 巴南区| 饶平县| 方城县| 凌海市| 衡阳市| 双桥区| 福鼎市| 衡阳市| 彭泽县| 南郑县| 彰化市| 嘉黎县| 登封市| 乌兰浩特市| 从化市| 扶余县| 郓城县| 德保县| 麦盖提县| 博罗县| 杭锦后旗| 四平市| 乐安县| 铜鼓县| 宁安市| 涟水县| 义乌市| 乌拉特中旗| 木里| 文登市| 塔河县| 昭通市| 繁昌县| 西丰县| 兰坪| 凭祥市| 胶州市| 抚宁县|