当 Controller 代码写在同一个 html 文件中时,代码可以工作。 但是,一旦我将 Controller 代码分离到 myController.js 文件中并在 src 属性中提及 js 文件,我就会收到 $injector 模块错误。 这是错误
Failed to load resource: the server responded with a status of 404 (Not Found)
angular.js:4547 Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it.
If registering a module ensure that you specify the dependencies as the second argument.
这是我的 Angular Controller
var app = angular.module('myApp',[]);
app.controller('myCtrl',['$scope','$http', function($scope, $http) {
$scope.submitForm=function(){
$http({
method:"POST",
url:"http://localhost:7000/frmAng/",
headers : { 'Content-Type' : 'application/json'},
data : {
name : $scope.name,
pwd : $scope.pwd
}
}).then(function(response) {
$scope.resFrmServer = response.data;
},function(response){
$scope.resFrmServer = response.statusText;
});
};
}]);
我该如何克服这个问题?因为,我想分离出所有 js 文件以进一步缩小。
带有 Angular 代码的完整 html 文件。
<!DOCTYPE html>
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js'></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl" align="center" >
<hr>
<form >
Name: <input type="text" ng-model="name" required autofocus><br><br>
Password:<input type="password" ng-model="pwd"><br><br>
<input type="submit" ng-click="submitForm()" text="Submit">
</form>
<h1>{{resFrmServer}}</h1>
</div>
<script >
var app = angular.module('myApp',[]);
app.controller('myCtrl',['$scope','$http', function($scope, $http) {
$scope.submitForm=function(){
$http({
method:"POST",
url:"http://localhost:7000/frmAng/",
headers : { 'Content-Type' : 'application/json'},
data : {
name : $scope.name,
pwd : $scope.pwd
}
}).then(function(response) {
$scope.resFrmServer = response.data;
},function(response){
$scope.resFrmServer = response.statusText;
});
};
}]);
</script>
最佳答案
希望您使用express.js来启用网络提供商。
如果您使用的是express.js,请使用以下代码来提供静态文件
app.use(express.static(__dirname + '/public'));
其中 public 是目录,所有静态文件都可用。
然后请将包含 Angular 模块和 Controller 代码的 js 文件放在 public 目录中,并从 html 文件中包含它。
关于javascript - 使用 Nodejs 运行服务器端时无法加载 Angular Controller 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246233/