How to put controller in another file in Angular 1.2? - javascript

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>

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

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

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

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', [....

Create an AngularJS module if it doesn't exist

I have several directives and factories spread over several files but I want all of them to be included inside the same module. For example:
user-account.js
var userModule = angular.module("user", []); //I create the module here
userModule.directive("userPicture", ...);
user-transactions.js
var userModule = angular.module("user"); //I use the module here
userModule.directive("userPayment", ...);
The problem I have is for this to work I need to include the files in the right order, otherwise it won't work since the creation of the module is only done in user-account.js. I don't like this since users for these modules would need to know the proper order for it to work.
So my question is, how can I structure my modules creation + usage in an elegant way? I was thinking on creating some kind of Singelton helper to create the module if it doesn't exist but I don't love the idea. Any other ideas?
Don't mix the user module and the user-account in the same file.
app.js:
angular.module('myApp', ['user']);
user.js:
angular.module('user', []);
user-account.js:
angular.module("user").directive("userPicture", ...);
user-transactions.js:
angular.module("user").directive("userPayment", ...);
And then in your index.html:
<!-- modules -->
<script src="js/app.js"></script>
<script src="js/user.js"></script>
<!-- directives -->
<script src="js/directives/user-account.js"></script>
<script src="js/directives/user-transactions.js"></script>
I would suggest using requirejs in that case. Then you won't have to worry about ordering of your script files.
I am following the style from the book Mastering Web Application Development with Angularjs, the link is the whole example explained in the book.
The main idea of this style is
1. Dived code by businsess feature instead of by type;
2. Put everything from one module into one file, like:
// myApp.js
angular.module('myApp', ['user']);
//user.js
angular.module('user', [])
.directive("userPicture", ...);
.directive("userPayment", ...);
//index.html:
<script src="js/app.js"></script>
<script src="js/user.js"></script>
Why doing that is no matter directives, service or controllers, they are talking to each other, in one file you don't need to switch files.
Yes, you may bloat up the model file, but it is good sign to separate into another model.
I am using that style in my projects, and I found the code much readable than before.

Categories

Resources