依赖注入允许你做几件事,首先它允许你在controller、factory、service等中只指定你需要的东西。
您有很多预置选项,但注入还允许您将第 3 方 Angular 模块合并到您的项目中。
例如,假设您想使用动画和路由,但您想使用 ui-router 而不是 ngRoute,而不是将它们注入到您的应用实例化中。
var myApp = angular.module('myApp', ['ui.router', 'ngAnimate']);
现在假设您已经设置了第一个控制器。
但是,假设您有一个服务,您想在该控制器中使用该服务,该服务使用 Promise 处理您的所有 ajax 调用。
首先,服务将被设置为注入$http 以发出服务器请求,$q 用于承诺。
// It is important to note that not all modules have a scope,
// so injecting scope into this service would cause a fatal error,
// it is important to become familiar with what baked in modules allow for
// injections.
myApp.service('myAjax', function ($http, $q) {
return {
getUsers: function () {
var q = $q.defer();
$http.get('my/url/path').success(function (results) {
// We got a successful response so pass on the results
q.resolve(results);
}).error(function (errorResults) {
// Something went wrong, let's pass that along
q.reject(errorResults);
});
return q.promise;
}
}
});
现在我们已经设置了服务,我们将把它注入到我们的控制器中,这样我们就可以轻松地使用它来获取用户或执行我们在其中声明的任何其他操作:
// Note that I am demonstrating a different injection approach, this is actually the recommended approach
myApp.controller('myController', ['$scope', 'myAjax', function ($scope, myAjax) {
// call our service
myAjax.getUsers().then(
function (results) {
// Here we are using our controller $scope injection to
// bind to the html
$scope.users = results;
},
function (error) {},
)
}]);
编辑
$inject 是$injector 的一部分,您可以找到more information here。
$injector 获取所有已注入的实例,$inject 只允许您设置注入参数。 $injector 在幕后运行。
Here is a snippet from the angular source on github - Line 1238
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = "World";
}
GoodController2.$inject = ['$scope'];