AngularJs Load dependencies files - javascript

I'm learning AngularJS and in all tutorials and screencasts I always saw to use angular writing code all in a unique file, example directives, controllers, factories etc...
Logically for large applications, you will split out the code, make it maintainable and flexible in multiple files and also we should be careful about how many <script> tags we have to require to let our JavaScript files run correctly.
I would like to know which is the best practice to require files when needed, importing less javascript files possible in my view. I took a look at RequireJs but it seems a bit complicated to use it. Is there some tool more efficient and easy to use? Or any good resource to get started?
A small example can be that I have a sort of plugin that has been built using directives, controllers and factories:
app-|
--Controllers
|_ pluginController.js
--Directives
|_ pluginDirective.js
--Factories
|_ pluginFactory.js
Instead of requiring all three files how do you make it work?

Here' a great example of how to use RequireJS and AngularJS together. It's a fork of the Angular Seed project and it should hopefully point you in the right direction. It comes with RequireJS baked right in. I definitely recommend learning RequireJS!

I would advice you to read up on dependency injection in the Angular documentaion. It all depends on how you set things up to be honest. If you want to use your service/factory in your controller then you would add the factory as a dependency in your controller or directive. See example below :
Angular.module('{YOUR MODULE NAME}').controller('{YOUR CONTORLLER NAME}', ['$scope', '{FACTORY NAME}',
function($scope,{FACTORY NAME}) {
}]
To invoke the directive within your controller, you would simply could simple add the directive to your controller template. This is a basic example, to learn more read about dependancy injectioninvoke

To be clear that I understand - e.g. I want to use "angularFileUpload" module, I need to add it to my module dependency list -
angular
.module('kids', ['angularFileUpload'
])
and load the script?
<script src="angularjs/plugins/angular-file-upload/angular-file-upload.min.js" type="text/javascript"></script>
Thanks for help.

Related

Using require js with angular js

I'm trying to use require js and angular js together. Referred to someone guides by googling:
http://marcoslin.github.io/angularAMD/#/home
http://www.sitepoint.com/using-requirejs-angularjs-applications/
Both guides seem to use angular, and angular-route and angular-amd, but I thought they were for other complicated purposes, so I only used "angular js" (so there is no shim in require.config()).
My main.js looks like this;
require.config({
paths: {
jquery : 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min',
'angular' : 'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min',
'class' : 'class',
'utility' : '../utility/utility',
},
deps: ['main1']
});
where deps: ['main1'] is the file to load right after require is defined as the first guide uses.
But I'm keep getting this error:
Error: $injector:modulerr
('UpdateApp' is the name of the app that I'm using in my project.)
And the webpage says that I get the error when I've forgotten to include the file with the defined module.
Not using deps: ['main1'] but using require(['angular'], function(){} and logging out angular.module('myApp',[]) logs Object nicely though. ... It seems like require(['angular'], function(angular) does not work but require(['angular'], function() works for me, and guides don't seem to tell me whether I should do the latter or the former.
I thought it would be as simple as adding angular js in paths, and loading it with require() or define() will work, but it's not...
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
Looking into your code, I can see that you clearly mis-understood about the concept of using requireJS and angular together. Either of the links you found are make by expert JS developers. Where both tried to combine angular and requireJS as simple as it could. So you need to accept the fact that it is complicated.
=> This is why I will not try to help you with some code. Because it will took lots of time and it will related with many topic which will not likely fit into a single question and answer on stackoverflow.
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
At first I want to repeat it. This is nothing like simple work. For requireJS you need to at least have advanced knowledge about what called AMD and able to imagine how things happen asynchronusly when requireJS trying to load an JS library.
Secondly, common knowledge about angular module/service injeaction. Since both requireJS and angular can do some sort of module/service injection you need to know about the difference between these two.
Third, the initial stage of your webapp. Since both requireJS and angular need to be initialled to run properly. So this will also the requirement.
Sum up
You will NOT able to understand both in a day or two. It will take time. But fortunately I have a couple of suggestions for you.
Research some about how requireJS and angular load their depenencies.
Go for angularAMD get the project seed. Set it up, run it, play with it.
Improve your knowledge about the initial state of both.
...
Profit!
P.S. just FYI. An year ago, I started with requireJS and angular. And I got hitted up with a big wall of knowleges, just like you. And these are what I have tried to understand them. Take your time, it is not like using jquery which can learn in a day or two. Even for some JS expert it took months just for them to confident about angular (not counting combine it with requireJS). Cheers!
Inside your main1.js you must be use require(['angular'], function(){} to start your application.
Require JS will give you a package dependency manager, concatenator/uglifier, javascript file loader, and an injector. Require JS injectors are used for injecting classes versus Angular, which is used to inject instances.
The big advantage is that RequireJS is going to speed up your application by managing your load and runtime dependencies. It's useful for big SPA's.
You can set up your file structure by defining all of your dependencies using "define". For functions to execute, you will need to use "require".
Here is a helpful video:
https://www.youtube.com/watch?v=4yulGISBF8w&index=1&list=PLgVbnDyASc1qDAam3Fe0f-u6u9MYL6pC8

Building Real World AngularJS apps, how should I declare my controllers in html. Do I need to declare all in the index.html?

I have an application based on e.g. the Northwind database, in which I have built views for each of the different objects to maintain them CRUD-ly, using AngularJS views and the in typical file structure adopted by most devs.
I have an issue I would like to improve, firstly from all examples I have seen, you need to declare your controller on an index.html file. If one module that a user uses does not require, all the other controllers, is it necessary to load all controllers on the client side. Is there a better way to only declare controllers that are need per view?
Is this the normal behaivor of a Single Page LOB, to preload all necessary dependencies, whether required or not?
No. Don't declare your controllers in your HTML.
The less logic you add in your template, the more flexible your app will be.
The problem with including controllers in your HTML is that if some nested controllers have the same instance var (example foobar), then you don't know which one would be displayed :
<div ng-controller="firstController">
...
<div ng-controller="secondController">
...
{foobar}
Then, the best way is to work with modules and routes. With routes, you can tell AngularJS that your HTML should be controlled by aController.
I you are looking for a good app to start with, take a look at this one.
It has been developped by the AnguarJS team and shows some good practices to follow. You can notice that none of the HTML files contain a reference to a controller.

Thinking in Angular Way

I am working on project with more than 1500 HTML pages.
This project was previously implemented in jQuery and JS code. Now I have to revamp this SPA using AngularJS.
I have gone through basics of angularjs. We have several interaction on in our projects (Moving from one page to another).
Is <head ngapp="routingApp"> is the right place to configure the routing for whole project or can I define it separately for each module?
As the project also uses jQuery for bootstrap dependency does it make any sense just to include jQuery for bootstrap?
I would strongly discourage you from declaring all your routing in one file. It will lead to really big file & bad maintainability.
If you have such a big project I'll advise you to read the Google's recommendation for AngularJS structure first.
Then every developer will have a way to 'scope' his work within one module & it would be easier for him to understand it.
Moreover it would be much easier to disable/enable some modules just by excluding them from final composing&"compilation" phase.
E.g. you'll have a module that defines routes that can be reached within this module.
I strongly recommend using Gulp & Bower (you'll have to have Node.js) to manage you dependency management as well as composition/compilation phase management.
As a teaser here you have gulp scripts compilation for fractal structure:
gulp.task('scripts', function () {
var depJS = dependencies.bower.js.map(function (dep) { return config.bowerLib + dep; });
depJS = depJS.concat(dependencies.node.js.map(function (dep) { return config.nodeLib + dep; }));
var srcJS = ['app/modules/app.js', 'app/modules/**/*.module.js', 'app/modules/**/*.js'];
var libPipe = gulp.src(depJS)
.pipe(plumber())
.pipe(concat('lib.min.js'))
.pipe(size({title: 'js-before lib'}))
.pipe(gulpif(config.minimize.perform, uglify(config.minimize.js)))
.pipe(size({title: ' js-after lib'}))
.pipe(gulp.dest(config.scriptsOutDir));
var pipe = gulp.src(srcJS)
.pipe(plumber())
.pipe(concat('all.min.js'))
.pipe(size({title: 'js-before all'}))
.pipe(gulpif(config.minimize.perform, uglify(config.minimize.js)))
.pipe(size({title: ' js-after all'}))
.pipe(gulp.dest(config.scriptsOutDir));
});
The second question - AngularJS have jQLite inside it. When the jQuery is available the jQuery implementation is used. (side note: use jQuery/jqlite only in directives). It depends how vastly the jQuery library is used throughout your project & what methods are used. Can it be replaced by jqlite (limited jQuery) or can you just rewrite all jquery specific DOM/etc. manipulation by directives.
You've mentioned bootstrap - did you mean Twitter Bootstrap? If so, look at the AngularJS UI-Bootstrap
You can definetaly separate it in modules, look at https://github.com/angular-ui/ui-router.
1.) If you are asking if its right to define whole routing inside 1 index.html and one angular app , yes it is right place. It is purpose of SPA

AngularJS application file structure

On a large AngularJS application having all my controllers in a single "controllers.js" file seems a little un-maintainable to me. Is there a better way to do this such as:
\js\controllers\myController.js
\js\controllers\yourController.js
\js\controllers\ourController.js
and that also applies for filters, services, directives etc...
There are lot's of ways to organize your code. You can look in the following links
Building Huuuuuge Apps with AngularJS
Code Organization in Large AngularJS and JavaScript Applications
AngularJS Best Practices: Directory Structure
You can follow their standard or you can make your own.
Try to follow the following guidelines:
Contollers shouldn't be too long, if it's too long then it is handling multiple responsibilities
Try to use Directives and Services in your system to reuse your code/logic
Directives are the most powerful things in Angualrjs, try to get maximum advantage of it.
Write Tests; even better you can try to practice TDD with AngularJS
You can manage it like module wise!!
For example , take user view , you make one directory, here its name is user!!
user // directory , now put all controller ,service and directive file into it !!
-- userController.js // controller file
-- userService.js // service file
-- userDirective.js // directive file
-- views // make directory, and put all html file regarding that module into this
--users.html // html file
Hope this will help you!!
See how these two starter projects organize files for a larger-scale application:
https://github.com/angular-app/angular-app/
https://github.com/joshdmiller/ng-boilerplate
You may wish to have a look at this community-driven guide.
The guide describes best practices for organizing the directory structure of a large AngularJS application.
It also makes recommendations on naming and structuring AngularJS modules, controllers, directives, filters and services.
It's also worth it to check out a tool like Lineman.js with the AngularJS application template.
For enterprise AngularJS projects, you may wish to look at this kickstarter which is based on ng-boilerplate.
There's a nice document out there from Google's own team that back up Shivali's example:
https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
Something like this:
sampleapp/
app.css
app.js top-level configuration, route def’ns for the app
app-controller.js
app-controller_test.js
components/
adminlogin/
adminlogin.css styles only used by this component
adminlogin.js optional file for module definition
adminlogin-directive.js
adminlogin-directive_test.js
private-export-filter/
private-export-filter.js
private-export-filter_test.js
userlogin/
somefilter.js
somefilter_test.js
userlogin.js
userlogin.css
userlogin.html
userlogin-directive.js
userlogin-directive_test.js
userlogin-service.js
userlogin-service_test.js
index.html
subsection1/
subsection1.js
subsection1-controller.js
subsection1-controller_test.js
subsection1_test.js
subsection1-1/
subsection1-1.css
subsection1-1.html
subsection1-1.js
subsection1-1-controller.js
subsection1-1-controller_test.js
subsection1-2/
subsection2/
subsection2.css
subsection2.html
subsection2.js
subsection2-controller.js
subsection2-controller_test.js
subsection3/
subsection3-1/
etc...
Check this, build your angular app with CoffeeScript, SCSS.
https://github.com/nhim175/modular-angular-skeleton/

How to load angular module

I've just started using angular and javascript and I can't really figure out how to structure my application.
I started writing a Controller and my first reflex is to put what I would call my model into a class in a different file.
I have different option
1 - putting everything (model + controller ) in one file
2 - using requireJS so my controller can 'include' my model. I've managed to do it, put it wasn't straight forward and I still have problem to make the yeoman dist version to work.
3 - use angular module, which seems to be the recommended way, but if choose this solution do I need to load explicitly my model file in the main html file. I understand that not hardcoding the dependency between files can be a good thing, so you can for example swap or change some components, but it seems wrong when for example a subclass need to requires its parent class. If I need to split a module in lots of angular submodules, do I need to load them all explicitly ? That's seem totally wrong.
Am I missing something ? what is the standard way to do so ?
What I found quite useful are the MTV meetup sessions. They give a good overview about how to apply best practices in AngularJS:
Best Practices: http://www.youtube.com/watch?v=ZhfUv0spHCY
Angular+Yeoman: http://www.youtube.com/watch?v=XOmwZopzcTA
There are many more videos on youtube. I hope this helps giving a first idea.

Categories