AngularJs Tutorial 5 – Simple File Uploader (With Custom Data) using AngularJS

Helllo Geeks!!!

(ahem… This is continuation from previous post http://code-like-a-poem.blogspot.in/2013/05/angularjs-tutorial-4-file-upload-using.html)

If you have looked at our previous example, we have added simple uploader using AngularJs. But, as the previous didn’t allow any custom form data to be sent. (Because… it don’t know how to do that time xD)

Well, anyway… i had time to find that blueimp does allow custom data to send!!

Changes: 1

upload_with_custom_data.html

As you can see, we have add two inputs ‘firstname’ and ‘lastname’ (just an example!)

Changes: 2

upload_with_custom_data.html

customdata=”customData()” -> This is where our custom data will appended to the directive

Changes: 3

todos_upload_controller.coffee

(For more about directive with ‘sending function’, see here http://docs.angularjs.org/guide/directive)

Changes: 4 (Finally!)


to

(Note: that we are stringify the data before sending http://msdn.microsoft.com/en-us/library/ie/cc836459(v=vs.94).aspx)

Well, that all guys! This simple file uploader is packed & loaded for any cases! You’ll be receiving your custom data as $_POST[‘params’] in your server (I added that too).

Enjoy!!!

For entire difference log: https://github.com/sk8terboi87/angularjs-tutorial/commit/b32bc4e226b5f57b07aca43b53a0a254b25e55d4#coffee/diretives/uploader_directive.coffee

For entire code: https://github.com/sk8terboi87/angularjs-tutorial/tree/learning

AngularJs Tutorial 4 – Simple File Uploader using AngularJS with CORS

Today, what we gonna see is ‘How to create a simple Uploader using AngularJs‘ taking following things in consideration.

  1. We need a Server to store our uploaded files with the help of CORS (Since we are keeping API in different server).
  2. We need to make our uploader as a easily re-usable component. I.e Directives in AngularJs

(For the impatience cats: https://github.com/sk8terboi87/angularjs-tutorial/tree/learning)

Instead of creating a complete uploader using jQuery(ofcourse) from scratch, we can use an already one available in the web. And, the best one is The Blueimp uploader. (I’ve been using this since past 2 companies and seriously, this is the best one.).

It worked beautifully with Play! Java, then Cake PHP and… now boys and pretty girls, we gonna use this with the all mighty AngularJS. Eventhough, BlueImp uploader already provide AngularJs support, but…em… hard to use it as a simple reusable thing. (which i need it by upcoming Monday D:)

But… Thanks to the http://shop.oreilly.com/product/0636920028055.do, (gave by my mentor) they provide a simple directive to do a nice CORS based angularjs uploader with blueimp jQuery project. But, then again… I really don’t like copy-pasting other guys codes(entire stuff), so, I’ve rewrote on my own (much more simple and re-usable, but all thanks to him)
So, lets get started… (pss, we are gonna continue from our previous done Todo application

http://code-like-a-poem.blogspot.in/2013/05/angularjs-tutorial-3-creating-simple.html

https://github.com/sk8terboi87/angularjs-tutorial)

Step: 1

Download blueimp using bower

Step: 2

Include required blueimp jquery files in our index.html

(Pss: Note that we got to include jquery before AngularJs)

Step: 3

Our custom uploader directive

Step: 4

Setting Up UI

I rewrote the actual example lil more customizable (may be not enough.. but, hey.. i tried)

As you can see, we included the directive ‘fileupload’ and passed several data to directive (know that, You SHOULD never send any data directly to a ‘directive’. i.e from controller to directive is wrong)

Step: 5

Setting Up Controller & Upload Service & Injecting in App.js

Thats it,

By now… you have simple working CORS based uploader using AngularJs and… it is simply re-usable. (yay :D)

Phew… It actually took only 15mins to write a working uploader & just an hour to customize it (and more than that for this blog xD)!! This simply shows the power of AngularJs in this reusable kinda of stuffs.

Here is the complete working copy 🙂


Note:

  • Don’t forget to change the upload url in app.coffee
  • I’m using blueimp server code from https://github.com/blueimp/jQuery-File-Upload/tree/master/server/php. For now, I’ve added that code in my UI itself in my checkout for now, make sure in put in different /var/www/ path and access that via yeoman running from 3501 port. This will show ya CORS implementation of our upload
  • IMPORTANT: 777 permission for files folder 😛

AngularJs Tutorial 3 – Creating a Simple Angular Application using Coffescript

Well guys and pretty girls, by now you have grasped how to structure folder and how to setup AngularJs.

(If not, http://code-like-a-poem.blogspot.in/2013/04/angularjs-tutorial-2-structuring-and.html)

So, lets go to next step for, “How to create a simple application using AngularJS” –  A Simple Todo Application! will do!


(Just a reminder before continuing,  this is not actually your hello world example or not advanced stuff either. Below example just puts in between for “how to get started using AngularJs for a real world application”. If you are completely new (i.e zero knowledge), follow their tutorial http://docs.angularjs.org/tutorial/step_01, then continue mine)

Step 1:  Plan! Plan!! Plan!!!

Lets get down with basics, for how to create your application, so, you need to know what-is-what in AngularJs (i.e, its capabilities, atleast, its basics)

Note: Since, its first for you kiddies, lets not worry about saving in a ‘database’, for now, we just save in local storage. (Its a feature in HTML5, a way to store things in browser, like cookies, but, better…pss, google it)

What we need,

  1. A Homepage
  2. A page where we need to provide a way to add a note
  3. Once, we added, we need to display it (better in the same page)

What we really need (er.. in programming ‘Angular’ way),

  1. Route for homepage
  2. Route for Add page
  3. View – To display the ‘add’ page
  4. View – To display the added ‘notes’
  5. Controller – Grabs the input from user  and send to a ‘service’ for saving the notes
  6. Services – Core process which saves the notes in ‘local storage’

Tips:

Service: In angularjs, its way of writing a reusable code. I.e, specific common tasks

Controller: Like any another MVC, business logic goes here baby! (but, in javascript)

Step 2: Creating a Module in AngularJs

Note: In every blog of mine, you’re gonna learn many thing along with one thing…. so, get used to it. will helpful for you to become a ‘nerdy geek’ :D. Here, we are learning Coffeescript

What we here did is created a module for our application named ‘angTut’ and set to a object variable for latter usage. As we go on, We will be creating controller, services, factories and so many hardcore angular stuffs for our application based on the module we have just now created!

Tips:

@angTut = , here creates ‘this.angTut =’

Note: In anytime you have difficulty understanding Coffeescript in the beginning, just to jump to my codes have a peek the javascript https://github.com/sk8terboi87/angularjs-tutorial/tree/master/app/scripts

But, seriously, you should learn to write coffeescript,

  • Its easy to write and clean to understand,
  • Will creates complex javascript fasters, simpler and mostly in proper ‘javascript’ way
  • The only minus is…. you might forget javascript :P… just peek at your javascript after it getting generated

Step 3: Creating routes in AngularJs

Note: Like already said, you can name your file in way you want and for proper programmer thingy, you should name ‘real properly’.

using $routeProvider you can create a route for our application. Above code is pretty understandable.

With the help of ‘config’ method in angularjs, we are injecting the $routeProvider in it. Then, inside we are creating a individual route for ‘homepage’, ‘add’ page and finally, a default route if nothing is matched.

Tips:

Hope you fellas using Sublime Text 2, just don’t forgot to install ‘CoffeeScript’ from package manager for Coffescript syntax hightlighting

Step 4: Creating a Controller in AngularJs

Note: All the links we access in web browser for angular js goes like ‘http://localhost:3501/#/add‘, note the ‘#’.

Now, If any one type the above url, we just to load the TodosController and the view in “views/Todos/add.html”

just like we created a route using ‘angular.config’, we are creating a controller and injecting ‘$scope’

$scope is everything in angularjs, all the data passed from view to controller and controller to view (remember the two-binding?) will available in $scope

And $scope.save is a function which will be triggered from view (don’t worry, i’ll show ya)

Tips:

Don’t forget to set a proper a tab size for making a code more readable. you can set tab size in ‘Settings – User’ in sublime editor. and use ‘indent as space instead of tab’ by clicking in lower right ‘Tab size’ display

Step 5: Creating a View in AngularJs

In our ‘add.html’, we need a form which should send a data to our controller

ng-submit – This takes of submitting data to our controller and save() should a method in our TodosController.

(How does it know it is in TodosController??  duh.. because we have said that in our routes :P)

ng-model – This is the two binding thing i was talking about. The value “ng-model=”note” will be available in our controller ‘TodosController , “save” method as $scope.note

Annnnnd…. any changes in $scope.note in our controller will be immediately updated in the view page. Tadaa… Two-way binding!!!

Tips:

note the ‘required’ keyword in <input… which does the minimum not empty client side validation. You can even write a depth client side validation using AngularJs

Step 6: Creating a Service in AngularJs

Now, once submitted, anything in input ‘note’ will be available in controller. what we now need to do is to store in ‘localstorage’ which i was talking about initially.

     Step 6.1:  Using a Third party module 

          There are many third party javascript libraries for AngularJs, we need a local storage library which  should lie between browser and our application

     To install the above,

    Step 6.2: Injecting a Third party module into our application.

         Now its available in folder, we need to our application so it can be used in our application for that, we need to inject into our module itself. In our app.js

        inject the name of the module we just have downloaded, which is ‘LocalStorageModule’.

 

Thats it!!! The rest of dependecy will be handled my AngularJs

Step 7: Using a Service in AngularJS

Now we have a layer ‘angular-local-storage’ which interacts with the browsers local strorage.

We can directly using it in our controller, right?? nope!!

You need to think….. that is providing another layer which interacts between the third party application and our controller, why? because, as we go on, later we might change this plugin or may be we just remove local storage and use a persistent storage. So, in order to avoid changing this is all of our controllers were we have used, we just write this code in a common place. i.,e ‘Angular Service’.

Note: Writing a service not only provide a common code usage, it also ease’s ‘unit testing’ which we will come later on.

Tips:

For making your code like more pretty,use single quotes instead of double (even if i used double in several places..whoops ^^”)

Oh, right… service!

Just like before, we are creating a service with the help of our module ‘angTut’ and name it as ‘todoService’

Inside we have created a function called ‘addFn’ and also, we have injected the ‘localStorageService’ (The actual third party service)

Thats it, we can write the ‘saving in local storage logic’ in ‘addFn’

Tips:

You can directly return the ‘addFn’, but, we have used ‘add:addFn’, because, later on, there will lot of get, set, blah.. blah.. function, and our code might look messy, doing this we can cleary see what are the avialble methods in services.

Step 8: Linking Controller and Services in AngularJs

Inject the service we have just created in our controller. and in our save method, we have called the add method in the service and also, we have passed the $scope.note, which has the input from the text box

Tips:

you might wanna switch to different files, for crying out loud, don’t open a folders and use your mouse and browse through all files and find it. In sublime text, use ‘ctrl + shift +r’ and starting typing the name of the file, thats it . (oh, don’t forget to import your project first)

Step 9: Linking all your Javascript files

If your following previous blog, “yeamon” will have converted all your coffee files into javascript files by now. Now, you need to link these scripts in index.html and let know our application is angularjs.

Step 10: Listing in AngularJs

Now you need to list all the datas you have saved in local storage. For fetching the data from local storage is same as i already said, just browse my for how.

In add.html,

ng-include – As you can see yourself, it inserts ‘list.html’ in our add.html. Even though its not really needed here, I’m just telling that, you can reuse ‘.html’ pages too!

In list.html

{{note}}

ng-init – On page start up, it triggers the list() function of the current controller, (in this case, TodosController)

ng-repeat – This is more like a for/foreach loop, which generates many <span>..</span> of {{note}} which is sub variable of notes json/array

Tips:

Make sure to close the </div> when using ng-include, else, the remaing html wont be render. Got me a headache for several minutes by forgetting this and also, notice, the single-quote inside the double-quote in ng-inlcude, which is also required. If you forget, angularjs wont say a thing >_<

Also, make sure, you read well of all “ng-” methods http://docs.angularjs.org/api/

Finally….

Now, every time you add something, all you need to do is update the $scope.notes, which will be IMMEDIATELY rendered in html without reloading the page (The magic of two-way binding)

The complete application is available in

https://github.com/sk8terboi87/angularjs-tutorial/

Browse the code for complete application. I know you, right now, you might not had complete clarity and little confused, which is good, this allows to you to learn more… by yourself. 🙂

So, pull the code and try it yourself. Comment your thoughts (not too much :P)

References

http://gregpike.net/demos/angular-local-storage/demo.html

https://github.com/IgorMinar/foodme/blob/

http://js2coffee.org/

AngularJs Tutorial 2 – Structuring and automating your application

Okkkay.. So, now you know something about AngularJs like i do.

Now, you gotta start to write your own application.  So how you gonna do it? Well, simple, write few files(index.html and script.js), link the AngularJs script, thats all!!

But, Yea… You’re forgetting an important point, that is, what if your Application grows? Everything grows in time, right? So, you must be sure to setup the files in a proper way, and thus by later adding should be easier than before, how do you do it??

There comes “Yeoman!!!” with their buddies “GruntJS” & “Bower

 

I’m not gonna talk about these stuffs coz they are already neatly told in their site, so, look into it.

With this, we can use Angular with Yeoman.

So, what I’m gonna to do is, HOW TO USE THESE STUFFS TO MAKE A COOL ANGULAR APP!!!

Here we go!!!

(Just a reminder before continuing, you actually don’t need to do below stuffs before working on AngularJs, you can just include the script in your html page and start working in it, its really simple. But, If you’re going to work on an application, you need proper setup, configurations, some automation (like auto page reload, auto coffee2js compilation, auto sass to css…blah..blah..).

Below steps may seem big, but, it wont take more than 15mins of your time, which will easy your work in the future)

For Windows:

  • Install Ubuntu 😛

For Ubuntu:

1) Install Yeoman

  Yeoman requires several stuffs to be integrated, but, they also wrote a cool script which does these stuff for you.

https://github.com/tomlane/Yeoman-scripts/blob/master/scripts/old-installer.sh

(One thing, I prefer ‘0.9’ Version, 1.0 seems still in beta and most importantly, i haven’t used yet :P)

2) Install AngularJs with Yeoman

3) PreCheck

With the Help of GruntJS, you can run this application in a separate port

Open the browser and hit <http://localhost:3501>

4) Install Bower

Why we need this?

As we go on, we start to require more and more external scripts and plugins. There will a ‘dependency’ issue. Bower, a cool thing, which manages these things

Save a ‘.bowerrc‘ file in your project path with the below content

Now, lets install ‘angular’

Now, you will see, it’ll download and save angular in ‘app/components’ folder and also, a ‘component.json’ in the application directory – The use of this file is, later, say you can manage version of these external library files and also, give to your colleage and ask him to run just ‘bower install’, these will automatically install all the packages mentioned in component.json

Note 1: You could do bower install from yeoman itself, but, for some reason, it doesn’t read .bowerrc config file 🙁 (or i don’t know how ^^”)

Note 2: Since, we are managing our dependency from components folder, you can remove the existing angular.js files from “app/scripts/vendors”

The idea is to move these dependency files/folder outside of our application.

Finally, You’ll Have this Structure

As, you move forward, say, you have a blog and blog user controller

But, the thing is, Angularjs doesn’t have any structure and naming conventions, its both good and bad.

So, you could follow any structure you can, but, make sure, you follow one (atleast one like I’ve used)

Okay…. Lets move on how to write a simple application using AngularJs with lil help from CoffeeScript 🙂

UPDATED!!!

For the folks who wanna jump started, I’ve added a Repo in GIT. Check it out (seriously, checkout :P)

https://github.com/sk8terboi87/angularjs-tutorial.git

(Branch: structuring-automatting)

Behold… AngularJs is here! About AngularJS for serious dummies!!

AngularJs for Beginners

Many of the Geeks around this year have started using AngularJS seriously! If you’re the one’em of the people saying … “uh.. what is AngularJS?”, You’re in the right place dude!! Because you better start using it now, its the next(already!) big deal in UI Development

AngularJS for dummies

So… what is AngularJS?

  • AngularJS is 100% JavaScript, 100% client side thing.
  • Powerful, Open-source JavaScript framework
  • Not exactly a MVC Framework, but much like MVW (Model-View-Whatever)
  • Mainly for building “Rich client-side applications”
  • Oh yea, It is Done & Maintained by Google!

Why AngularJS

  • Extends HTML vocabulary, (i.e) Use HTML special markup for angular to extend your application
  • Provides lot of flexibility to separate presentation logic from business logic and presentation state… and much more!

Standout Features in AngularJs

1) Two Way Data-Binding

2) Hail…. Dependency Injection!

3) MVW

4) REST

5) Deep Linking

6) Unit Testing & E2E Testing!

What you shouldn’t do?

1) Try not to mess up with DOM directly, AngularJs does for you

2) Don’t combine much jQuery in Angular.js, Refer: http://docs.angularjs.org/api/angular.element, only if not present go for jQuery

How it Works?

It really look complicated in the beginning to understand, may be you can leave this for later.

Still curious, check here!

More About The Features:

1) Two Way Data-Binding

In simple terms, (If you have framework idea), “Whatever you change in VIEW, will be reflected in MODEL Automatically, and vice-versa!” Cool-huh?

Still don’t get it?

2) Dependency Injections

It call is simple (again), DI is… Magic! DI is how use/inject a dependency of other class into the class you’re using! They way you’re using, shouldn’t complicate your unit testing. To get a clear idea, what is DI, check here!

3) MVM

AngularJs is called MV* Framework. I.e, Model-view-whatever framework. It has some advantage when you’re building application by separating you’re presentation and business logic layer.Check this post for more about this!

4) Unit Testing

With Great Code comes Great Unit Testing. Nevertheless of any language, your code should be Unit testable.  AngularJS written in a way which is perfect for unit testing. Preferably, Jasmine http://pivotal.github.com/jasmine/

Difference between Angular.js & Backbone.js

Data-binding
The most prominent feature that separates the two libraries is in the way models and views are synchronized. Whereas AngularJS supports two way data-binding, Backbone.js relies heavily on boilerplate code to harmonize its models and views.
REST
Backbone.js communicates well with RESTful backends, while AngularJS’ $http service is more flexible, connecting to remote servers either through a browser’sXMLHttpRequest object or via JSONP.
Templating
To handle views, AngularJS uses customizable HTML tags. Backbone.js, on the other hand, requires a templating engine, such as Underscore.js.

http://en.wikipedia.org/wiki/AngularJS#Comparisons_to_Backbone.js

Also, Check it out the difference between jQuery & AngularJs here. There aren’t the same!

So, shall we get it started?  AngularJs Tutorial 2 – Structuring and automating your application

If you wanna find more resources for angularjs, peek here