Angular.js Novice to Ninja controllers - javascript

I have been trying to learn some Angular.js using Angular.js Novice to Ninja.
The main problem that i have by now is that in the examples you have to files, app.js and controller.js.
The main module is declared in app.js and controllers.js as dependencies:
angular.module('myApp', [
'myApp.controllers',
'ngRoute'
]);
In controllers.js, controllers are declared like this:
angular.module('myApp.controllers').controller('BookController', function($scope){
$scope.name="Scope for BookController";
});
but it never works like that, i have to do this and keep everthing in the same file.
var app=angular.module('myApp', [
'myApp.controllers',
'ngRoute'
]);
app.controller('BookController', function($scope){
$scope.name="Scope for BookController";
});
Can someone tell me what is wrong? Thank you.

What does your debugger say?
My guess is you're loading the files in the wrong order. You see, you have to first define myApp.controllers to be able to load it in myApp, so make sure your controllers.js is injected first, and then app.js.

Please make sure that you load the files in following order in head tag,
<script src="/path_to/angular/angular.js"></script>
<script src="/path_to/app.js"></script>
<script src="/path_to_controllers/controllers.js"></script>
Also please add following line to the app.js,
myApp.controllers = angular.module('myApp.controllers',[])
And change your code to following in controller.js,
myApp.controllers.controller('BookController', function($scope){
$scope.name="Scope for BookController";
});
Hope this will resolve your issue.

Related

How to "import" a controller.js file in the angular.module file

I'm just starting to learn Angular so the issue I'm trying to figure out here might be a bit awkwardly formulated. I'll try my best and explain what I'm dealig with.
I have a main main.js module file where I have declared
angular.module('app', [
'ngRoute'
])
Now I have a separrate file for the controller as home.controller.js which contains
angular
.module('app')
.controller('HomeController', ['$scope', function($scope) {
}]);
Is there any way to include the home.controller.js file withing the main.js file without having to put the script src in the html ? I have tried to import 'path/home.conntroller.js but I get this error
Module 'app' is not available! You either misspelled the module name or forgot to load it.
Appreciate the help.
Make sure main.js is included in your HTML file before home.controller.js ... for example:
<script src="main.js"></script>
<script src="home.controller.js"></script>

Angular uncaught reference $injector

I'm new to angular and am having trouble set my project up. I have tried everything I have seen on google and stackoverflow(please do not send link to similar question).. None have worked. Im using angular 1.5.5 and refer to the cdn. here is what my code looks like. Thanks!
<html ng-app="boatup">
<link href="css/one-page-wonder.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="mainCtrl">
</body>
//in app.js
var app = angular.module('boatup', [
'boatup.controllers',
'ngRoute'
]);
//in controllers.js
app.controller('mainCtrl', function($scope) {
console.log("hello");
});
The error is angular.js:38 Uncaught Error: [$injector:modulerr] in angular.js 38
Thanks for any help in advance.
Uncaught reference error in angular is caused when you are either using a module with no definition or the file with the module definition is not loaded in scripts. You have not declared the boatup.controllers module but added it as a dependency to your main module. Either declare and define boatup.controllers or remove it as a dependency as below:
angular.module('boatup', [
'ngRoute'
]);
Replace this with your code.
//in app.js
angular.module('boatup', [
'ngRoute'
]);
//in controllers.js
angular.module('boatup')
.controller('mainCtrl', function($scope) {
console.log("hello");
});
As far as I can see from your description, you've started your project with creating different files with your application's modules. That's a good descision. But!
You instantiated your main app's module and assigned it to global variable app. It's not that big deal, but better avoid creating unnecessary variable in global scope. And if you devine gloabl variable app in different files, it will be owerwritten with the last file loaded.
You must load your module with controllers before main module. Otherwise you'll get [$injector:modulerr].
So in your case the following solution will work.
controllers.js
angular.module('boatup.controllers', [])
.controller('mainCtrl', ['$scope', function($scope) {
console.log('hello');
}])
app.js
angular.module('boatup', ['ngRoute', 'boatup.controllers']);
And you need to load in appropriate order.
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-route.min.js"></script>
<script src="controllers.js"></script>
<script src="app.js"></script>

Angular: [$injector:modulerr] Failed to instantiate module

I've been trying to set up basic AngularJS functionality for a project but have been hitting a brick wall when it comes to including angular-route. Both are version 1.4.8. I'm currently using gulp-require to concatenate my JS, here's my main javascript file
// =require ../components/jquery/dist/jquery.min.js
// =require ../components/angular/angular.js
// =require ../components/angular-route/angular-route.js
$(document).ready(function() {
// =require app/app.js
}); // Doc ready is done!
And my app.js file
var app = angular.module('myApp', ['ngRoute']);
app.controller("ctrl", ["$scope", 'ngRoute', function($scope) {
$scope.test = "It works!";
}]);
I've checked and all the files are concatenating properly. The ng-app and ng-controller attributes are on my HTML file. I've tried adding and removing the ngRoute injection and switching the order of the files but to no avail. It's frustrating since I used Angular 1.4.5 in almost the exact same way without these issues popping up but I can't replicate the same here even when going back. But the {{test}} variable in my HTML is still not rendering, and basic operations like {{2 + 3}} aren't either.
EDIT: here is the link to the original error message I'm currently receiving: http://tinyurl.com/zx3k85f
EDIT 2: The parts of my HTML code that's calling the app and the controller:
<html lang="en" ng-app="myApp">
<body ng-controller="ctrl">
</body>
</html>
I'm using nunjucks for HTML dynamic generation, although I've changed the syntax for this so it doesn't conflict with Angular's double curly braces.
You can't inject module as dependency inside controller, you should remove 'ngRoute' from the controller DI inline array.
app.controller("ctrl", ["$scope", , function($scope) {
Update
Basically the real problem is you are loading your angular component script using requirejs(lazily), so while you are having ng-app="myApp" with module name start looking for myApp module, and the module has not loaded therefore it throws an error .
So I'd recommend you to don't use ng-app directive to start angular on page load. Instead you should wait until all the scripts related to angular loaded, & then to bootstrap angular app lazily using angular.bootstrap method.
Code
$(document).ready(function() {
requirejs(["app/app.js"], function(util) {
angular.bootstrap(document, ['myApp']);
});
});
ngRoute is a provider that needs to be configured in the module config section before being used. Using it within a controller does not make any sense. Here the version that will work:
angular.module('myApp', ['ngRoute']);
angular.module('myApp').controller("ctrl", ["$scope",function($scope) {
$scope.test = "It works!";
}]);
Moreover, you need to call your module using directive ng-app=myapp in the html element where you plan to render your app.

AngularJS Controller is not a function error

I'm getting error when adding ng-controller="HeaderController" to a div.
Error: ng:areq
Bad Argument
Argument 'HeaderController' is not a function, got undefined
my HTML looks like that:
<div ng-app="myApp">
<div ng-controller="HeaderController">
</div>
<div ng-controller="PostController">
</div>
</div>
Also I include following files:
MyApp.js
var myApp = angular.module('myApp', ['postServices', 'angularFileUpload', 'ngSanitize', 'ui.date', 'bootstrapLightbox', 'profileServices']);
HeaderController.js
myApp.controller('HeaderController', ['$scope', 'PostServices', '$http', function($scope, PostServices, $http) {
$scope.getBookmarksCount = function() {
PostServices.getBookmarksCount().then(function(response) {
if (response.data.status == 'success') {
$scope.bookmarksCount = response.data.bookmarksCount;
} else {
$scope.errorMessage = response.data.message;
}
})
};
}]);
PostController.js beggining of this file looks like:
myApp.controller('PostController', ['$scope', 'PostServices', '$http', 'FileUploader', 'Lightbox',function($scope, PostServices, $http, FileUploader, Lightbox) {
PostService.js contains a module named postServices and it contains a service PostServices:
angular.module('postServices', [])
.service('PostServices', ['$http', function($http) {
if I delete ng-controller="HeaderController" everything works fine.
Does anyone knows what could be the problem?
In your module you add the postServices without a capital at the start, while you add it in your headercontroller as PostServices. This might mess with the forming of your headercontroller.
Either one of those could be a typo, but it is very important that you inject the service precisely as it is defined (in your .service or .factory) in the ['PostService', bit. So if the service is called: postService, you should inject it in your controller as: ['postService, function(someNameThatDoesntMatter) if its called PostService, inject it as ['PostService', function(someNameThatDoesntMatter)
As I just shown, how you call it afterwards in the function parameter is up to you.
Update
You could create a module for your controllers to fix this. Make sure to inject your postServices in this module aswell. Then inject the controllers module in your myApp module :-) The benefit of working in a structured way like this, is that you can create a structure of including your JS which you can apply on every project you work on.
I don't know which version of Angular you use , I took 1.4.0 for my plunk example and try just to limit to the code you provide to see if I recreated the error.
I had to deal more with scripts inclusion order. It created error. The right order in order to make it work is
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.4.0/angular.js"></script>
<script src="MyApp.js"></script>
<script src="PostController.js"></script>
<script src="PostService.js"></script>
<script src="HeaderController.js"></script>
http://plnkr.co/edit/NhzQFmI1s9r98uAMZwYg
So Main point was to defined PostService.js before HeaderController
It seems likes
you forget include that HeaderController.js file in index.html.
Make sure your HeaderController.js is loaded properly.
Missing some where in gulp/grunt process.

Angular.js - can't inject external module

I'm trying to make the simplest possible website setting, where I have an Angular.js app with single module depending on one external module (for example Restangular).
I don't know why, but I can not get it working. I'm getting get this kind of error:
Error: [$injector:unpr] http://errors.angularjs.org/1.2.17/$injector/unpr?p0=restangularProvider%20%3C-%20restangular
Actually, it doesn't matter that it's restangular - I've tried it with other modules and the result was analogical.
I have created a plunker that shows my problem:
http://plnkr.co/edit/3ZUoDYtd4sVTT7nLpURi?p=preview
But there is not that much code - I will paste it here too.
In my index.html file I include angular.js, lodash.js (required by restangular), restangular.js and my application's script.js files with tags.
This is the body of my html:
<body ng-app="example" ng-controller="AppCtrl">
<p>Take a look into console... Restangular can not get injected. What am I doing wrong?</p>
</body>
And this is the content of script.js:
var app = angular.module( 'example', ['restangular'])
app.controller('AppCtrl', ['$scope', 'restangular', function($scope, Restangular) {
console.log(Restangular);
}]);
As a note - in the console I can do this:
angular.module('restangular')
but, this does not work:
angular.injector(["ng"]).get('restangular')
It seems that I'm missing something basic about Angular.js. Help will be appreciated...
Could it be this?
app.controller('AppCtrl', ['$scope', 'Restangular', function($scope, Restangular) {
Restangular hast to be written with a capital R
You wrote
app.controller('AppCtrl', ['$scope', 'restangular', function($scope, Restangular) {
At least now I see in the console
URL visited /edit/3ZUoDYtd4sVTT7nLpURi
editor-0.7.30.js
Object { configuration={...}, requestParams={...}, defaultHeaders={...}, more...}

Categories