Reputation: 953
when the controller code is written in the same html file, code works. But as soon as I separate the controller code into myController.js file and mention the js file in the src attribut I get an $injector module error. This is the error
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.
This is my 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;
});
};
}]);
How do I overcome this ? As, I want to separate out all js files for further minification.
Complete html file with angular code.
<!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>
Upvotes: 0
Views: 1294
Reputation: 953
// [ route.js ]
app.get('/myController.js',function(req,res){
res.sendFile(__dirname + "/client/" + "myController.js");
});
adding a route to my controller, this was the missing part. As, I'm new to node, I wasn't aware that files mentioned in the "src" of the "script" tag too requires routes. I thought node'll simply use the file protocol to fetch those files.
Comment by Patrick is a better workaround.
Upvotes: 0
Reputation: 106
Hope you are using express.js for enabling web provider.
If you are using express.js, please use following code for supplying static files
app.use(express.static(__dirname + '/public'));
where public is the directory, where all static files are available.
Then please place your js file, which contains angular module and controller code, in public directory and include it from html file.
Upvotes: 1