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
Related
I will read/write a file with angular from/to my hdd. I normaly use node module "fs". Whats the best practice to combine this module with angular to use it in node webkit?
Thanks!
Edit: (can't use require in angular to load npm modules. any ideas?)
.service("WindowService", WindowService);
function WindowService() {
this.gui = require('nw.gui');
}
i wrote this example, if you had any questions as to how things are working? you may also want to check out this as well, which the former example uses to work outside of the browser.
but since the main question is regarding the error involving the require function, i will elaborate. require is a function implemented by the node runtime, it was added because there was no way initially built into js to import code from fileA to fileB. so when your in the browser you dont need to require anything, just make sure you have the file added to the html ie: <script src="my/file.js"></script>. but if you really want to do require in the browser, just use browserfy.
I have similar experiences to you. I usually wrap modules to services and use it as normal angular service with DI.
This makes code more readable and maintanable. Also, when you want to change node module, you are changing it in one place.
for your project, i will look to
socket.io > for broadcast websocket, and update your angular scope...
shokidar > better than FS, with less bug than fs
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'm an experienced javascript programmer, and I'm trying to write my own modular game engine from scratch. I haven't used requirejs before, but after reading a bit about it, it sounds like it's probably the best way to manage all the components of the engine and load them into one coherent structure.
My main problem is that I'm not really sure how to really use requirejs. I've been looking over their API documentation, but I'm not sure how to integrate it with the way I've laid out my project.
Currently, my project uses the following structure:
src
engine.js //This contains the common engine stuff, most notably the engine namespace
resource
resource-module.js //This is the module constructor, which handles all the common stuff between the different
substructures
sprites.js //This is a substructure that contains sprite loading code
render
etc...
third-party
jquery
requirejs
I want to be able to load the modules independently of each other. It should be possible for instance to remove the audio module from the engine, and it still work. It should also be easy to substitute modules, or add new modules.
Also, I'm using jQuery for event handling, so it needs to be loaded before the engine is initiated.
You can find my current source here: https://github.com/superlinkx/lithium-engine
I know the current code is messy, and there isn't a whole lot built yet, but I'm mostly still figuring out how to best structure it. Any help/advice would be appreciated, but my main concern is how to structure it with requirejs so that it will be easier to compile into a single file for production use.
Require.js does not enforce any specific structure of your files. You can either specify the full paths in the require configuration, or just use the full path in the require() or define() calls. Both will work, however the latter will save you some typing and makes it easier to move stuff around when you include something from a lot of different places:
var $ = require("third-party/jquery");
require.config({
paths: {
"jquery": "third-party/jquery"
}
});
var $ = require("jquery");
I want to be able to load the modules independently of each other. It should be possible for instance to remove the audio module from the engine, and it still work. It should also be easy to substitute modules, or add new modules.
This is not something require.js does four you. You can decide when and when not to load it, but you would have to make sure that it won't break the rest of your code.
Also, I'm using jQuery for event handling, so it needs to be loaded before the engine is initiated.
You can do this in several different ways.
require() it in your main.js so that it is always loaded (you can also use the require-jquery.js, which has jQuery included).
Specify jQuery as a dependency of your engine
require.config({
paths: {
"jquery": "path.to.jquery",
"engine": "path.to.engine"
},
shim: {
"engine": {
"deps": ["jquery"]
}
}
});
Pass jQuery to the define() call in your module (probably the best choice)
define(["jquery"], function ($) {
// your engine code
}
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.
I'm working with a very large project that uses:
Legacy JSP pages that includes javascript files with script tags
Backbone models and views that uses other javascript modules without RequireJS
We now want to start using RequireJS with jQuery, BackboneJS and UnderscoreJS for everything we develop from now on, but we don't have the resources to rewrite all the legacy JSP pages. We may have time to rewrite the Backbone models and views we have already developed.
The problem is that for our legacy code (both 1 and 2 above) we include all our javascript files in a huge file and ship to the browsers. This huge file must be able to co-exist with our new RequireJS templates, but how can I e.g. separate certain parts of the huge file, so I can use them with the templates using RequireJS? Without having to rewrite all pages that uses this part of the file, or having duplicate code.
Thanks!
I don't know if I fully grasp the problem at hand, but I think a the shim or map functions of RequireJS will help you out.
Extract the parts you want in a new module from your huge javascript file. Then tell RequireJS that your huge javascript file is a dependecy for this new module using shim. Something like:
requirejs.config({
shim: {
'new-module': {
deps: ['huge-javascript-file'],
exports: 'NewModule'
}
});
Shim documentation: http://requirejs.org/docs/api.html#config-shim
The map function might be useful when only portions of your new code have to use your old huge file. Check out this documentation: http://requirejs.org/docs/api.html#config-map
I don't think there is One True Way to achieve this, but I've approached a similar problem by defining module "facades" around the globally scoped code. Let's say your legacy scripts define a global variable called foo. You can define a AMD module and export that variable from it:
//foo.js
define(function() {
return window.foo;
});
//bar.js
define(['foo'], function(foo) {
//do something with foo
});
This way you only need to write a single-line facade every time you need to use a new piece of the existing, globally defined code, without breaking existing code which expects the same code to be globally defined. Over time you can move and refactor the actual implementation into the module without breaking consumer code.