AngularJS Separating The Controllers, Argument is not a function, it is undefined - javascript

I know it is asked hundreds of times, but I cannot really find out the error. I have looked all the similar questions At first, I did everything in one page, it was working, but obviously I needed to learn to separate my controllers to different files. I have did the following:
partials/hosts.html:
Hosts Page
<div ng-controller="HostsCtrl">
{{ title }}
</div>
index.html
<html>
<head>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap.min.js"></script>
<script src="js/myApp.js"></script>
<script src="js/HostsCtrl.js"></script>
</head>
<body ng-app="MyApp">
...
js/MyApp.js
Create MyApp module, and a submodule named controllers
var app = angular.module('MyApp', ['ngRoute', 'ui.bootstrap']);
console.log("index.js file loaded");
angular.module('MyApp.controllers', []);
js/HostsCtrl.js
Just a simple controller in MyApp.controllers module that displays hello world and time.
console.log("HostsCtrl.js file loaded");
angular.module('MyApp.controllers').controller("HostsCtrl", function($scope) {
$scope.title = "Hello world" + new Date().getTime();
});
The console output:
index.js file loaded MyApp.js:2
HostsCtrl.js file loaded HostsCtrl.js:1
Error: [ng:areq] Argument 'HostsCtrl' is not a function, got undefined
I assume the loading order is correct, however I do not understand why it gives an error and cannot resolve HostsCtrl. What am I doing wrong?

Looks like you never declare MyApp.controllers dependency (since your controllers are in separate module). Try this:
var app = angular.module('MyApp', [
'ngRoute',
'ui.bootstrap',
'MyApp.controllers'
]);

Related

not able to create controller by referencing to javascript file having module declared in it

I created angular module in a javascript file app.js as below:
var app = angular.module('myApp', []);
Further i went to the controller folder of my project and added a javascript file for Controllers.
Next i referenced the already created app.js file(which is havning module creation) in the first step and then i tried to create controller using it as in below lines:
/// <reference path="app.js" />
app.controller('myctrl', function ($scope) {
$scope.tesdtata = 'test';
})
Now when i am binding the scope variable to UI and running the solution, i am getting exceptions as: 'app' not defined
Finally i am not able to vied the value of 'testdata' in browser.
Moreover when i type the line: app.controller(..) the intellisence shows me some diffenet overload variables i.e. app.controller(recepiename,factoryfunction) which is not correct.
Everything works fine if i create module individualy for every controller file and then using that create controller in same file. And problem occurs when i try to reference the single app.js file (having module creation it) and try to create controllers.
Check if your UI(HTML file) looks something like this. That'll do.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script src="app.js"></script>
<script src="control.js"></script>
</head>
<body ng-controller="myCtrl">
{{testdata}}
</body>
</html>
It is discouraged to use global variables in javascript nowadays.
Instead of doing this
// app.js
var app = angular.module('myApp, []');
// controller.js
app.controller...
Do this
// app.js
var app = angular.module('myApp, []');
// controller.js
angular.module('myApp').controller...
Reference not needed and intellisense won't complain too.l

How to print Hello World in angularjs

I am trying to print Hello World in AngularJS, I have created javascript file named testControllerbut unfortunately it shows this error
here is HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS</title>
<script type="text/javascript" src="../../app/controllers/testController.js"></script>
</head>
<body ng-app="app">
<div ng-controller="testController">
<h2>{{message}}</h2>
</div>
</body>
</html>
and this testController code
var app = angular.module("app", []);
app.controller("testController", function ($scope) {
$scope.message = "Hello, AngularJS";
});
Where is the issue ? can anyone explain ?
Error clearly stated that testController function haven't got register in app module. There is possibility that there could be more files involved in your application(you have shrink the code to have relevant information in post). It seems in each file you're redefining module every time before registering angular components like below
var app = angular.module("app", []);
app.controller("myOtherController", function ($scope) {
//Code here
});
So in this case what had happened is, app got created once again, and old registered component got wiped out. myOtherController got registered with app module. To fix the issue you should not be declaring module again & again. Define it once and use it in other places.
app.module.js
angular.module('app', []);
testController.js
angular.module("app")
.controller("myOtherController", function ($scope) {
//Code here
});
I could not find anything wrong with you code. So I tried it on works fine for me.
Plunker https://plnkr.co/edit/xSKHe6?p=preview
Check Module Error: https://docs.angularjs.org/error/$injector/nomod?p0=app

Angular module failed because of improper loading

I am using the angular-seed project as an example for my own project.
I create the app module in app.js, like the angular-seed.
"use strict";
// Declare app level module which depends on views, and components
angular.module("myApp", ["ngRoute", "myApp.home"])
.config(["$routeProvider", function($routeProvider) {
$routeProvider.otherwise({redirectTo: "/"});
}]);
I then create my myApp.home in another file.
"use strict";
angular.module("myApp.home", ["ngRoute"])
.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/", {
templateUrl: "views/home/home.html",
controller: "HomeController"
});
}])
.controller("HomeController", [function() {
}]);
I load the two in my index.html file like this:
<script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-route/angular-route.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="views/home/home.js"</script>
Angular cannot instantiate the app because myApp.home is not available. I assume this is because I am loading app.js first. And it is looking for myApp.home which is not loaded yet.
Is this something Angular should be taking care of, or do I need to
create a build process?
After reading online, I cannot find a solution that works for me, maybe I am overlooking something silly.

Angular JS Injecting Custom Service

I can't get angular to accept my custom service, which is in a seperate file. I know this is all over stack overflow, but I just can't tell where I'm messing up.
Html:
<!DOCTYPE html>
<html lang="en" ng-app="angularApp">
<head>
<!-- ANGULAR -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-sanitize.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.js"></script>
<link href="styles/angularApp.css" rel="stylesheet">
<script src="scripts/controllers/angularApp.js"></script>
<script src ="scripts/services/clearCodemirror.js"></script>
Main angular javascript file (contains my controller)
var myApp = angular.module("angularApp", ["ui.codemirror","ui.bootstrap", "ngSanitize", "ngRoute"]);
myApp.controller("mainController", ["$scope", "$timeout", "clearCodemirror", function($scope, $timeout, clearCodemirror){
Service I'm trying to inject:
var myApp = angular.module("angularApp");
myApp.service("clearCodemirror", function(cm){
Error I keep getting:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.6/$injector/modulerr?p0=angularApp&p1=Error…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.6%2Fangular.min.js%3A29%3A56)
I only included the beginnings of each file so you guys wouldn't have to wade through tons of code. Where am I screwing up?
Thanks!
By calling angular.module("angularApp") from your 2nd file, you are recreating a angular module, and NOT getting a reference to the module that was created on the previous file.
There are a few ways to solve that. The simplest one (on my point of view) is to set your angular app to a window.VARIABLE.
window.myApp = angular.module("angularApp", ["ui.codemirror","ui.bootstrap", "ngSanitize", "ngRoute"]);
Then, from your 2nd file you can:
var myApp = window.myApp;
myApp.service("clearCodemirror", function(cm){
There are better ways to do that. However, this one you get you going. Cheers!
Hi you are not re creating the module you are getting the existing module by var myApp = angular.module("angularApp");
as the docs states :-
https://docs.angularjs.org/api/ng/function/angular.module
When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.
i tried with 1.3.14 , i didnt got any error, which version are you using:-

Run angular.js as a callback ($.ajax, for example)

I'm writing an app with mostly two javascripts, resources_loader.js and app.js, where the first loads some json files used by app.js.
The problem is: app.js (which has angular.js stuff) should run only after resources_loader.js. I tried to run angular code inside the success callback (resources_loader contains a deferred), but this not seems to work well. Here's my index.html:
<!doctype html>
<html ng-app="myapp">
<body>
<script src="angular.js"></script>
<script src="resources_loader.js"></script>
</body>
</html>
Consider that I moved app.js to resources_loader, inside the success callback. Everytime I try to run it, angular raises the following exception: Uncaught Error: No module: myapp.
My guess is that angular.module('myapp', []) should run before onload's event, which is not the case here.
Another thing is that I want to use yepnope.js in my project like this:
<script "yepnope.js"></script>
<script "resources_loader.js"></script>
<script>
var loader = load_stuff();
yepnope({
test: loader.resolved(),
yep: ['angular.js', 'app.js', 'foo.js', 'bar.js'],
nope: ['fail.js']
});
</script>
app.js contains angular code. I think it's more performant because it only loads angular if the resources are loaded. But how can I do it?
Remove ng-app from <html> tag and use angular.bootstrap(document, ['myapp']); to fire it up once your resources are loaded, like this:
var app = angular.module('myapp', []);
app.config(['$routeProvider', '$locationProvider', function($router, $location) {
$location.html5Mode(true);
$router
.when('/', {
templateUrl: 'some_template.html',
controller: 'myController'
});
}]);
// and then, after everything, run
angular.bootstrap(document, ['myapp']);

Categories

Resources