angular.injector
描述:
创建一个injector对象, 调用injector对象的方法可以获得angular的service, 或者用来做依赖注入.
使用方法:
angular.injector(modules, [strictDi])
参数详解:
Param | Type | Details |
---|---|---|
modules | Array.<string|Function> | 一组module或者他们的别名. ng module需要显示地申明出来. |
strictDi
(optional)
| boolean | Injector需不需要使用严格模式,即允不允许使用默认别名 (default: false) |
返回值:
Injector对象.
示例代码:
1. 一般情况下次函数用来做单元测试啦, 我这边的示例比较为了示例而示例
<!DOCTYPE HTML>
<html ng-app="exampleApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.7.2.min.js"></script>
<script src="angular.min.js"></script>
<script>
var exampleApp = angular.module('exampleApp',[]);
exampleApp.controller('exampleController',['$scope', function($scope){
$scope.name = "boyi";
$scope.inject = function(){
var $injector = angular.injector(['ng']);
$injector.invoke(function($http) {
var scopes = angular.element(document.body).scope();
scopes.name = "博弈网络";//这里可以同http请求获得数据
});
};
}]);
</script>
</head>
<body ng-controller='exampleController'>
<div id="test">博弈网络科技</div>
<div>{{name}}</div>
<div><input type="button" ng-click="inject()" value="injector"/></div>
<hr>
</body>
</html>
2.
当
Angular的app
已经启动编译好了之后,
有时候你又想强行进入做一些逻辑或者修改,可以使用JQuery/jqLite元素的injector()方法
<!DOCTYPE HTML>
<html ng-app="exampleApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.7.2.min.js"></script>
<script src="angular.min.js"></script>
<script>
var exampleApp = angular.module('exampleApp',[]);
exampleApp.controller('exampleController',['$scope', function($scope){
$scope.addElement = function(){
var div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
$(document.body).append(div);
angular.element(document).injector().invoke(function($compile){
var scope = angular.element(div).scope();
$compile(div)(scope);
});
}
}]).controller('MyCtrl',['$scope', function($scope){
$scope.content = {"label":"testing"};
}]);
</script>
</head>
<body ng-controller='exampleController'>
<div id="test">博弈网络科技</div>
<div><input type="button" ng-click="addElement()" value="addElement"/></div>
<hr>
</body>
</html>