Angular JS Injecting Custom Service - javascript

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:-

Related

How to put controller in another file in Angular 1.2?

I'm trying to separate the controller file from the module file (in app.js). But executing this in browser gives me an error. It works only if I put controller and module code in one file. But doesn't work if I put contoller in another file.
Here's my code for module (app.js):
var CoursePlannerApp = angular.module("CoursePlannerApp", []);
And for the controller (CoursePlannerAppCtrl.js file):
CoursePlannerApp.controller("coursePlannerCtrl", function ($scope) {
});
Can anybody explain me please, why it doesn`t work? Thanks.
In your app file
angular.module('app',[]); // initialise application
In your controller file
angular.module('app').controller('myCtrl', [function(){}]); //create controller
And make sure you loaded both files into the browser - app and than controller
If you are not working with some kind of bundler (like webpack), you put all of your files on the global scope, therefore, you should manage the order of loading the files.
At your case, you should put app.js to load before CoursePlannerAppCtrl.js. In that way, app.js will put CoursePlannerApp on the window, and you will have an access to it from CoursePlannerAppCtrl.js.
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="CoursePlannerAppCtrl.js"></script>
You need to include the script tags in correct order. Just like below
<script src="../lib/angular.js"></script>
<script src="CoursePlannerApp.js"></script>
<script src="coursePlannerCtrl.js"></script>

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

Angular - scripts load order

I've just started with Angular after many years working with MVC. I'm quite familiar with js, HMTL but still beginner in the Angular world.
I lost 3 hours trying to figure out what is wrong with my app.
So the app has 3 files
index.html
<body ng-app="perica">
<p>main</p>
{{ tagline }}
<a ng-click="logOut();">Logout</a>
<div ng-view><p>inside</p></div>
</body>
<script type="text/javascript" src="../components/angular/angular.js"></script>
<script type="text/javascript" src="../AgularApp.js"></script>
<script type="text/javascript" src="../controllers/AcountController.js">
AngularApp.js
debugger;
angular.module('perica', ['ngRoute']).config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
console.log('in');
debugger;
$routeProvider.when('/test', {
templateUrl: 'views/Account/_Login.html'
})
$locationProvider.html5Mode(true);
}]);
and AccountController.js
var myApp = angular.module('perica', []);
myApp.controller('AcountController', ['$scope', function ($scope) {
$scope.tagline = 'The square root of life is pi!';
}]);
So as you can see it is a super simple application.
By all the coding logic, I should load angular core scripts the first, then my angular app and at the end angularcontroles.
When I run the app, Chrome hit the first debugger (above angular.module inside AngularApp.js file) and jumped straight into AccountContoler.js and completely ignored what is defined inside of the AngularApp.js.
but
When I reversed paths and put first AccountController.js and afterwards AngularApp.js everything worked without any issue
I would be really grateful if someone can shed some light on this issue
Thanks!
By using...
var myApp = angular.module('perica', [])
... in your AccountController.js, you're not loading your already existing 'perica' application (declared in the previously loaded AngularApp.js):
you are re-defining the perica application.
The correct way to refer to your already existing module is using:
angular.module('perica')
^
no dependency declared
instead of:
angular.module('perica', [])
^
dependencies
The logic behind this is quite simple once you're acquainted to it: if you're declaring dependencies while "loading" a module, you're creating that module. Otherwise, you're referring to it.
TL;DR: You're basically using a setter here twice and never actually enhancing your existing module.
Here's a working JSFiddle (link) with your application running. I loaded AngularJS directly from the Javascript framework/extensions menu and referred to an external JS resource for angular-route (fetched from cdnjs: https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js).
I basically simply concatenated both your AngularApp.js and AccountController.js contents to emulate loading them one after the other.
Please note that your also have to declare the controller that controls your view: I took the liberty to enhance your <body ng-app="perica"> element as follows:
<body ng-app="perica" ng-controller="AcountController">

loading multiple modules in angularjs

I'm constantly getting this error -
https://docs.angularjs.org/error/$injector/nomod?p0=interactive-main
The project structure (with multiple people developing and all new to angularjs) looks like this -
public
|--css, font-awesome
|--js (where angular.min.js and other jquery libraries are)
|--views (where html for each pages are)
|--myHTMLcontents
|--js
index.html
The index.html has it's own data-ng-app name and it's used in the app.js file.
I have my HTML files in the views folder, and the corresponding js files are in the views folder also.
I tried to create with
angular.module('myApp').controller(....
But I guess you're supposed to only create angular.module once (which is in the app.js), but I'm still unsure how to add 'myApp' in app.js.
I tried to do this:
(function () {
angular.module('data-ng-app Name', [
'ui.router', // Routing
'oc.lazyLoad', // ocLazyLoad
'ui.bootstrap', // Ui Bootstrap
'myApp'
])
})();
The nodejs server doesn't throw error, but nothing shows on the page (after I added 'myApp').
How do you solve this?
You need to create the module 'myApp' once and run it in app.js.
below is an example.
angular.module('myApp', []).run()
And then in your controller
angular.module('myApp.controllers', []).controller('RegisterCtrl', function () {});
First make sure your declare the myapp module file in your index before inject it into an other one :
<script src="js/myapp.js"></script>
<script src="js/my-module-injecting-myapp.js"></script>
Then two ways :
The first one is directly calling the module, by the way you did :
angular.module('myApp').controller(....
The second and what I used to do is declaring it as variable:
var myAppModule = angular.module('myApp', []);
Then to declare a controller, service , whatever, just call the variable:
myAppModule.controller("myAppController", function(){...
One last thing, I don't know if was an example but do not declare your module name with space :
angular.module('data-ng-app Name', [....
should be :
angular.module('myModuleNamewithoutSpace', [....

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

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'
]);

Categories

Resources