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.
Related
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
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.
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.
I use require.js to do lazy loading for a Javascript app. I would love to switch to a meteor stack but right now it looks like Meteor sends the whole app (all the templates) through on the initial load. Has anyone had success with require.js and meteor or any other implementation?
You're asking different questions, but certainly they are connected. The first is about loading additional javascript code into your meteor app. Of course you can use thing like requirejs. This should work fine supposing your lazy code is located in the public directory of your meteor project. However, my experience is that requirejs goes mad when the contents of public gets updated often, so for example in the development environment. Maybe it's a matter of customizing the library, but I would rather recommend using some lightweight homebrewed package. Look here, if you need some inspiration.
The second question is about lazy template definition. Each template consists of two parts. The first is its html code, written in handlebars syntax, the second is all the javascript code which you write to define how your template should behave (e.g. helpers, event handlers). The second part is easy, as long as we assume that we already know how to load the lazy code (see the above paragraph) and the template, lets call it myLazyTemplate, is already defined, so basically speaking Template.myLazyTemplate is not undefined. So how to achieve the latter?
To dynamically define a new template you'll need to call
Template.__define__(name, raw_func)
on the client. So the last question is "what is raw_func?". This is a compiled version of your html code which is normally created automatically on the server and then sent down the wire to the client when the app gets loaded (look here to see how it's done in meteor). But we want to do it dynamically, right?
So the idea is to compile the template code manually with a help of the Handlebars.to_json_ast routine. You can feed it with your template html code, and the output is some javascript array that can be sent to the client anytime by the method we've already talked about. The last thing you need to do is to call Handlebars.json_ast_to_func on the client, using the data sent from the server as the only argument. The output produced by Handlebars.json_ast_to_func is the raw_func you can use to produce myLazyTemplate template.
I'm aware that this is only a rough idea, not the whole solution to your problem. I hope this will help you to figure out the final solution on your own.
I'm starting in javascript development, and did a simple project with node.js as a rest API and a client using backbone, everything look perfectly till I want to get my templates out of my js.
I found different approaches, some of them with some time (like one year old) but I can't understand which one could be better:
A .js file with a var with the html code
pros -> easy to load, easy to pass to underscore to compile it.
cons -> scape every single line.
app.templates.view = " \
<h3>something code</h3> \
";
load template:
template: _.template(app.templates.view)
External template in Underscore
Use require.js to load with text plug-in.
pros -> load different templates as needed.
cons -> I don't like the approach to put everything inside a "loader" function...
define(["TemplateEngine", "text!templates/template.html"], function(...
RequireJS: Loading modules including templates and CSS
A function that loads the templates with an AJAX petition.
pros -> You can load the template that you need and adds local storage posibilities.
cons -> Seems that I have to merge all my templates into one file for production environments.
function() {
var templateLoader = {... $.get calls ...}
Best way to asynchronously load underscore templates
And a Jquery plug-in for template loading that I really liked but it seems that it didn't go to release?
http://api.jquery.com/jQuery.template/
It seems that require is the best approach, but maybe I'm missing something, I do wan't to make things as clean as possible since I'm in the learning/having fun phase :D
Any good article or github project with a good structure or any light on this will be appreciated.
Thanks.
Excuse any major spelling mistake, not an English speaker :)
--EDIT--
found some interesting videos to understand how to start and wrap things with require.js
http://www.youtube.com/watch?v=VGlDR1QiV3A
http://www.youtube.com/watch?v=M-wjQjsryMY
I would recommend using require.js with text plugin. Mixing html templates as strings in javascript variable is bad idea, as well as using something like <script type="text/template"></script>.
Here is one very good series on backbone.js which covers template loading and project build as well: http://dailyjs.com/2012/11/29/backbone-tutorial-1/. Github project is also provided there.
Require is a good option from the ones you listed.
Is there a reason you haven't considered simply:
Storing templates in the pages that use them as <script type='text/template'> nodes?
Storing templates as text (non-JS) files and loading them via XHR on pages that use them?