Angular 依赖注入

angular 使用模块化组织方式,依赖注入的设计,这使得模块间的耦合度降低,模块更容易复用。同时支持声明式编程风格。

AngularJS通过依赖注入方式实现模块化与封装。

在angular中,一个module通常对应一个js文件,其包含config,controller,service,filter,directive。

angular.module('myApp', ['ngRoute','ngResource'])
    .config(function($httpProvider){
        $httpProvider.defaults.headers.post['acception/json'];
    })
    .controller('myCtrl', function($scope, $http){
        $scope.user = ['alice','bob'];
    })
    .directive('custom',function(){
        return {templeteUrl:'tpl/custom.html'};
    })
    .filter('count',function(){
       return function(content){
          return content + "个";
       }
    })

其中myApp是模块名,ngRoute和ngResource是依赖模块

$httpProvider是配置Provider,myCtrl是controller,$http是依赖服务

custom是自定义指令

count是过滤器

依赖注入  

在angular中,Controller,Directive,Filter,Service都是以工厂方法的方式给出的,而工厂方法的参数名对应着该工厂方法依赖的Service。

如:

app.controller('myCtrl',function($scope,$http){
   //...
})

在上述function执行前,Angular Injector会生成一个$scope实例和$http实例,并传入该方法,如果,你希望对JS压缩处理,那么参数名就有可能发生变化。Angular Injector将不能正确地注入依赖的Service。于是,有另外一种写法:

app.controller('myCtrl',['$scope','$http',function($scope,$http){
   //...
}])

以字符串数组的形式来声明依赖数项,因为字符串常量不会被压缩。  

  

原文地址:https://www.cnblogs.com/WaTa/p/5740377.html