我想(通过异步http请求)限制AngularJS模块的创建。
这是HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#edit-field-resource-type').change(function(){
var v = $(this).val();
$('.all-options').hide(); //hide all the divs first, then only show the ones you want to show
if(v==='something-1'){
$('.something-1').show();
}
else if(v==='something-2'){
$('.something-2').show();
}
// and so on...
});
});
</script>
</head>
“ app.js”的内容:
<html>
<head>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script type="text/javascript" src="./app.js"></script>
</head>
<body ng-app="myApp">
<nav>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</nav>
<div ui-view></div>
</body>
</html>
我在$http = angular.injector(["ng"]).get("$http");
$http.get('http://demo0719583.mockable.io/weather')
.then(function(response){
var myApp = angular.module("myApp",[ "ui.router", "AppCtrls"]);
myApp.config(function ($stateProvider, $urlRouterProvider){
$stateProvider.state("state1", {
url: "/qsd",
template: "<p>State 1</p>",
controller: "Ctrl1"
}).state("state2", {
url: "/aze",
template: "<p>State 2</p>",
controller: "Ctrl2"
});
});
var ctrls = angular.module("AppCtrls", []);
ctrls.controller( "Ctrl1", function($scope) {
console.log("Ctrl1 loaded.");
});
ctrls.controller( "Ctrl2", function($scope) {
console.log("Ctrl2 loaded.");
});
}, function(errorResponse){
alert('duh !');
});
之外使用$http
,以便可以触发异步http请求。
该请求有效,但出现以下错误:
angular
我的猜测是声明的angular.js:36 Uncaught Error: [$injector:modulerr]
等待一个模块,但是由于异步,该模块的创建被延迟了。
问题:如何以编程方式创建模块并避免该错误?
致谢。