MEAN - Angular - JS - Extend server.js - javascript

After a few days and weeks of programming an application based on MEAN, I got to the problem, that the usualy called server.js-file gets bigger and bigger.
It contains the application setup and configuration, also in there is the Angular-Routing and the Mongod-Queries. So you can imagine...
So my first question is, how to extand the file? For example, what do I need to do, that the Routing is in another file and also the queries are seperate and the application still finds the "way" to it.
Another topic but similar problem: The html-files are big and unclear to read, cause the Navbar (for example) is in each page, but has always the same code. So how would it be possible to inject that specific code into each html-page?

If your HTML file is getting large and difficult to manage and you are using the MEAN stack then you can write a new angular directive to help split up your html into smaller more manageable parts.
Write a new directive in angular for example.
angular.directive('navbar', function(){
return {
restrict: 'E'
templateUrl: 'yourpath/navbar.html
}
Now in your html all you have to insert is the following:
<navbar></navbar>

Related

What's best practice re. isolating JS to pages/actions within a Rails project?

For the first time as a jnr progammer I'm looking at how to write my js code so that it's isolated to certain pages within my Rails app. I figure this is a sensible thing to do for the purposes of;
a) certain js i write I only want to target a certain element on an individual page, not other elements on other pages within the same controller that may get picked up due to using a class selector for example and marking every single thing with unique id's doesn't seem too neat. (I see that rails already has controller isolation through the naming of js files by controller, but further dividing things up into action/page names js files doesn't sound nice either!).
b) perhaps in finding a solution to only running js on certain pages it could mean that the js only needs to be loaded on certain actions thereby saving on load times.
There's a well attended question here with folks approaches here but most answers are 6 years old now and another nice post about the so called 'Garber Irish method of Dom ready execution' here that sounds quite nice, but again this is quite old now and all based on Rails 3...
So without wanting to create duplicate content I'm seeking to get a refreshed answer to this same question and find out whether there's a best practice now established these days.
Thanks
Convention:
Rails when using scaffold generator by default creates corresponding
app/assets/javascripts/MODEL_NAME.coffee
app/assets/stylesheets/MODEL_NAME.scss
which separates JS and CSS logic by "controller" name
Personal Preference:
Rather than controller-based segregation, I prefer layout-component-based segregation. Best explained through a sample code below:
app/assets/javascripts/application.js
//= require_tree ./layouts/
app/assets/javascripts/layouts/__shared.coffee
// WRITE GLOBAL JS LOGIC HERE FOR ANY LAYOUT
app/assets/javascripts/layouts/application/__shared.coffee
// WRITE GLOBAL JS LOGIC HERE ONLY FOR THIS "application" LAYOUT
app/assets/javascripts/layouts/blog/__shared.coffee
// WRITE GLOBAL JS LOGIC HERE ONLY FOR THIS "blog" LAYOUT IF YOU HAVE ANOTHER layout such as "layouts/blog.html.erb"
app/assets/javascripts/layouts/application/components/header.coffee
// WRITE JS code here for the header component
app/assets/javascripts/layouts/application/components/footer.coffee
// WRITE JS code here for the footer component
app/assets/javascripts/layouts/application/components/users/__shared.coffee
// You can also divide a component into subcomponents just like this
// WRITE JS code shared amongst all users subcomponents
app/assets/javascripts/layouts/application/components/users/form.coffee
// WRITE JS CODE HERE regarding the form that creates or updates a User
app/assets/javascripts/layouts/application/components/users/list.coffee
// WRITE JS CODE HERE regarding the table listing all users
You also structure the CSS files in the same way, matching the components

Is it possible to influence a single Angular app from multiple JS scripts?

Quick Summary:
I need to allow two script files to handle different operations for the same angular app. One needs to initialize the app, the other needs to assign a templateCache object to a piece of JSON in localStorage.
Context:
I have several python files which compile/generate html and I have constructed an angular app with this emitted html for my site (which uses CGIs).
The basic construct of the site comes pieces of HTML, which fit together like so:
|------------Header---------------|
|-Navigation-|------Content-------|
|-Navigation-|------Content-------|
|-Navigation-|------Content-------|
|------------Footer---------------|
My Header creates the <head> tag, instantiates my ng-app and uses $templateCache to set up a template that I call from my Navigation code. I had to go with templateCache instead of ngView and ngRoute due to some limitations with how the CGIs emit the html, and the order in which this happens.
My "Navigation" python/html sets up my app with JS like so:
<script>
var responsiveCatalog = angular.module('responsiveCatalog', ['ngStorage']);
....controllers...
....config, etc....
</script>
This Navigation also includes my default templateCache object:
<div ng-include=" 'responsiveItems.html' "></div>
This is all working to show my first templateCache object in the Content section. However, I need to grab many pieces of information from the python generator for the "Content" section (a totally separate file from the "Navigation"), store this data as JSON in localstorage (hence the inclusion of the ngStorage module), and call that as my second templateCache option.
I am not actually sure that I can use two separate instances of Javascript to reference and influence the same Angular app. I know this seems like bad practice, but I am trying to prevent the need to tear down a huge piece of legacy architecture to influence the angular app from two Javascript files in harmony.
Thanks in advance.
You can do
angular.module('myAppName').controllers.... in different files, just make sure the myAppName the same. Bug I don't feel like it work with config, no time to test. If you need any communication between them, check $emit and $broadcast.

Lazy Loading templates in Meteor

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.

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.

Whats the best way to structure my js application, when my views / controllers need to be in the same file

I am Building a learning application where there are a bunch of different page types that a learner will go through and do activities. It will be a SCORM compliant learning object.
This is the structure I have so far...
application/
models/
scorm.js
sequence.js
session.js
pagetypes/
multichoice.js
truefalse.js
basic.js
utilities/
jquery.js
api.js
My pagetypes do the viewing and the controlling, should I seperate these out? The reason I have combined them is so when I build a new page type, I can just drop it into that folder and it will get recognised straight away by the code.
What do you guys think? amidoinrite?
I'm guessing you're separating out methods based on type of page interactions.
I don't see any reason not to do it your way. So long as everything the sco needs is in the manifest you can subdivide your scripts however you want. It might save just a bit of load time to separate out separate page types... But only if you are only loading what you need into the HTML page, & you are actually navigating pages within a sco session. If you're loading all script into a single HTML page, & then dynamically changing the content of page divs, then your scripts are all loaded 1 time & you may as well have 1 minified file for all page type scripts.
I would probably go with the latter, & tie interactions to classes or ids in the markup. 1 file, less work to minify, & I can use in other packages without having to make sure that I have every page type I need...
With JavaScript it can be tricky to separate it out since it lives so closely to the view. As long as the data is separated from the actual view (which it looks like it is in your example) it will be a good design. I would argue that the pagetypes are more controllers and the HTML is the view. The most important part is to keep the model separated from the view. Unless you're trying to build reusable JavaScript/HTML components it's ok for pagetypes to blur the role of controller and view.

Categories