AngularJs Tutorial 8 — Simple Notification Directive Using Event Dispatcher

Now this is fast, my second article in a day. I guess its the only way to stop thinking about ‘She-Who-Must-Not-Be-Named’. Well coming to matter at hand, I worked in AngularJs for a while and always missed a good notification thingy. Twitter Bootstrap notification seems good, but, so static like a zombie. So, finally thought of creating one angularjs tutorial! A simple angularjs notification plugin/component.

Also, we are going to learn something new along the way

Event Dispatcher!!! (Taa-daa!)

Wait a minute, AngularJS has “Event Dispatcher“?? Yep! They do… and they are done using “Angular $emit“, “Angular $broadcast” and “Angular $on

Ok, before going deep, why the hell should i use “Event Dispatcher” if i could do a simple inheritance like function call?!!

Answer: Some actions or asynchronous activity should be handled in a way which shouldn’t alter the existing application flow. Like in our case, even if notification doesn’t work, its a not big deal, but, it shouldn’t interrupt our actual application flow.

And geeks used to call this as Observer pattern.

Some other good examples are ‘logging’.

Generally, an Event has ‘Publisher’ and ‘Subscriber’. In our case,

  • Publisher – $emit & $broadcast. The difference between both of’em are
    • $emit – dispatches the event upwards through the scope hierarchy.
    • $broadcast – dispatches the event downwards to all child scopes,
  • Subsciber – $on

Now, for our example we need existing cool notification library and Noty (http://needim.github.io/noty/) is one of the few best notification plugin library available. (simple and… cool)

                                         


Checkout -> https://github.com/sk8terboi87/Just-Anguled

1) jade/index.jade

2) coffee/directives/notificationDirective.coffee

3) coffee/controllers/NotificationController.coffee

4) coffee/kickstart.coffee

As you can see:

(1) Like before we created a directive, with 4 params. 

  • Always remember the rules, the only way to send a message to a directive must be through ‘isolated scope’ else, its not a reusable component. Each should independent!

(2) Our ‘notifcationDirective’. Pretty understandable!


(Note: Here we added a “$watch” on ‘uuid’. Because, we need to know whether the data outside our directive gets changed or not. Suppose, if we watch on ‘message’ and message is same for the second trigger also, $watch thinks as the previous one. So, we are watching something which changes on every action trigger.)

(3) Our Event Publisher, its Publishes data when button gets triggered

  • $scope.$emit('notifyEvent', notifyData)  – eventName and eventData (2 params)

(Note: Here we are just manually triggering sending the data. We can easily changed to how we need)

(4) Our Event Subscriber, Receives the data whenever a publisher pushes the data

  • $scope.$on(‘notifyEvent’, (event, data) 
  • From here, we are pushing the data to our jade/index.jade where our directive is located.

Thats it!! Now, try clicking all the actions….. pretty cool, huh! (Check their plugin for more options to meddle with)






(I know, screenshot is worse xD)

Thats it for now!!! An event handling in AngularJs is so very easy peasy.


Check it out —> https://github.com/sk8terboi87/Just-Anguled

References:

  1. http://stackoverflow.com/questions/14502006/scope-emit-and-on-angularjs
  2. http://docs.angularjs.org/api/ng.$rootScope.Scope
  3. http://needim.github.io/noty/

AngularJs Tutorial 7 — Creating a Simple Component using Directives (with a Charts example)

Its been a while. (seriously!), its like getting awake from incubation chamber and write another angularjs tutorial!!

And, today we gonna see AngularJs Directives.

Why should i use Directives?!

  • Reusable components!
  • NEVER manipulate DOM from your Angular controller/anywhere except via directive

They are…  “A powerful tool for modifying the DOM”. As we know, AngularJs does the compilation stuffs of DOM and any other event related to it and if we directly add some event (like we do using jQuery) is seriously wrong. We surely end up messing AngularJs.

To handle this, Angular Js Directive provides a methods such $compile, and whatever we mention their will get compiled by AngularJs itself.

AngularJs Compilation Cycle:

Compile function:

  • Used for template DOM manipulation ,
  • Provided by directive, (Hence manipulations that apply to all DOM clones of the template associated with the directive.
  • Ex: Manipulation of tElement = template element)

Link function:

  • Used for registering DOM listeners and as well as updating the DOM.
  • It is executed after the template has been cloned — e.g., inside an <li ng-repeat…>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element.
  • Ex: $watch expressions on the scope, manipulation of iElement = individual instance element

Now, getting back to our example, but  before that I’m not gonna start teaching from “Hello directive”. Eventhough AngularJs documentation sucks, go through it anyway, we will get a basic idea. http://docs.angularjs.org/guide/directive

Now, lets see the AngularJs directive using ChartJs

And here is the Repo : https://github.com/sk8terboi87/Just-Anguled

1) jade/views/charts/index.jade

2) coffee/kickstart.coffee 

3) coffee/directives/piechartDirective.coffee


As you can see:

(1) We just created a directive element called trackr-piechart using an Element.

(Note: You can even create element like <div trackr-piechart=''></div>, but, as conventation to be followed according to AngularJs,

  • Use an element when you are creating a component that is in control of the template.
  • Use an attribute when you are decorating an existing element with new functionality.
  • Also, make sure to keep a ‘prefix’ for your directive element, (if in case, may be in future HTML 8 or 9 and there already existing an element ‘<piechar..’> might clash with ours. so go with prefix! 🙂

)

And, we have passed ‘title’ and ‘data’ to the directive

(2) Injection and defining our chart module

(3) In Piechart directive, we have used

  • @chartModule – using the chart module we have created to make a directive (watch the naming convention of the directive with the element, it matters!)
  • scope – Making it isolated scope. so can can use many ‘piechart’ individual components multiple times in a page.
  • restrict – Restricting only to ‘E’ means element.
  • templateUrl – We are keeping the template separate, though you can keep it here itself. Might look ugly if the template starts to grow
  • link – Whatever mentioning here will be added to the link cycle of AngularJs

Thats it. Add some data in our controller and which it make a beautiful piechart. Easy peasy!!!

(Experiment: copy and paste many <trackr-piechart> and provide different data they will work independently thats how a component should be!!! (Thank the isolated scope)

Now, the disadvantage of isolated scope is, you cannot directly tie the controller to our chart directive.

(4) coffee/directives/linechartDirective.coffee

For this, checkout our second linechart example

Setting ng-model

As you can use, we tie the input title to the directive template and added a $watch in our directive to know anything changes. Thats it!!!

Check it out —> https://github.com/sk8terboi87/Just-Anguled.git

References:

  1. http://chartjs.devexpress.com/Demo
  2. http://docs.angularjs.org/guide/directive
  3. http://stackoverflow.com/a/12570008/1172872

AngularJs Tutorial 6 — Pt 3 — Building a RESTful Application With PHP & MongoDB

I guess all the people are same, inside. All they want is fun and when commitments comes by, they say ‘Ta-Ta’!!!. God, when are they gonna learn “You have to fight for something u believe in and nothing can be obtained without sacrificing certain things’….But, I have no regrets, I gave everything, but, you will have.

“If you love somebody, let them go. If they return, they were always yours. If they don’t, they never were.”

Anyway, back to topic.

Our final tutorial in building a Restful API – AngularJs & PHP (with MongoDB) is Complete!!!

So, What are the things we gonna see…

  • [API] – CORS!!!
  • [UI] – Advanced concepts in AngularJs $resource & Custom reusable resourceFactory

CORS – “cross-origin resource sharing”

It means “Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries.

To explain it simple, “Generally, One(web) cannot access or request or send resource to another domain, unless both present in same site(According to “Same Origin Policy“!). What CORS does is, it provides a way for cross domain access by specifying certain things in ‘header’ request, thereby allowing a site from another server can access!”

Example:

In our example, our PHP application runs in default ’80’ port. However, our AngularJS UI is executed via Yeamon-GruntJS, which is in 3501 port. So, when runned in browser, both act like in different server and our poor AngularJs cannot access our PHP/API part. 🙁

But, not to worry, Here comes CORS!!!

(https://github.com/sk8terboi87/simple-restful-tutorial-api/blob/blogs/app/index.php)

As you can see, all our response in our API are send to this ‘responseHandler’ method where we have specified our CORS.

Check here for detailed information about it

  1. http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
  2. http://enable-cors.org

Note: Normally, to enable CORS, you first have to send a ‘pre-request or pre-flight request’ from UI (before making the actual request). That is an “OPTIONS” (similarly to GET, POST…).

But, AngularJS is nice enough to send it automatically, so you don’t have to worry about it when using $resource.

Advanced concepts in AngularJs $resource

“AngularJS Promise variables – $then & $resolved”

Before jumping into this, some have no idea what this is.

In our blogs application, we are making a request to fetch all ‘blogs’ from API and display in a nice tabular form.

Our code is something like this,

The second line makes an ajax call to API, and the result is binded to ‘$scope.blogs’ as expected. But, JavaScript goes in ‘asynchronous’ way, what happens is, before getting the result, our third line will be executed, which causes ‘undefined’ thingy!!!

To solve this, we need to make certain things in our code, ‘synchronous’, i.e We need to bind our ‘$scope.blogs’ only when we get response from ‘blogResource’. This is where AngularJs ‘$then & $resolved” comes in.

For updated code looks like this,

‘$then’ from AngularJs will be executed only when response comes in. Thus making our two-binding works nicely.

(Note: Older version of AngularJs $resource will not send $then)

And our lastly, our Reusable ‘resource factory’

https://github.com/sk8terboi87/simple-restful-tutorial-ui/blob/blogs/coffee/Services/resourceFactory.coffee

This is a separate AngularJs factory which we used along with the controller showed before. We can use this simple usable resource methods for all of our new modules, say ‘Users’ or ‘Categories’ or ‘whatever’. Just inject in our controller, thats all. You can easily make a any kind of calls to our API.

(Note: PUT request is not directly available by AngularJs $resource, so, you noticed the difference in our code)

Thats it for our Simple Restful tutorial!!! Even though my explanation seems lil big, just browse the code to know how simple this is :). Just small bunch of files which creates an entire CRUD application.

What we have so far done is just a start, we will slowly continue to evolve… to next level. So, be sure to be with me 🙂

(And don’t forget to share :P)

AngularJs Tutorial 6 — Pt 2 — Building a RESTful Application With PHP & MongoDB

Finally, I’m trying to make peace with myself by throwing those harmful thoughts into the oblivion (without actually falling into it). Everyone does know the term ‘she’ – can either kill or let you live.

Anyways…. Well, I hope you fellas have the idea about our previous thing http://code-like-a-poem.blogspot.in/2013/08/angularjs-tutorial-6-building-restful.html.

In this tut, we are gonna see how the API stuffs does it work and return backs the response to our blog tut.

So, What are the things we gonna see…

  • What the heck is REST & Why we need to use?
  • Building our Application as RESTFul Service using PHP Slim Framework and storing in MongoDB.
  • Sending back the Response to our AngularJS

What the heck is REST & Why we need to use?

“Representational state transfer or REST is a style of software architecture which conventionally consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. – wikipedia

Previously, people used ‘web services’ using SOAP. There are lot of good things on using a RESTful service

  • Less overhead (no SOAP envelope to wrap every call in)
  • Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope).
  • More standardized – HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.
  • More human readable and testable (harder to test SOAP with just a browser).
  • Don’t need to use XML (well you kind of don’t have to for SOAP either but it hardly makes sense since you’re already doing parsing of the envelope).
  • Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. yes in theory SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you’ll ever do is over HTTP

Building our Application as RESTFul Application

Now, you have the idea what is REST thing, the ingredients to make our application are,

  1. PHP Framework, Slim Framework will do (since your app is not that big)
  2. To store our data, we choose Mongo (Read here for more intel)

Traditionally, we use to install to our third party packages by,

  • Visiting there download page and click download
  • Unzipping, keeping in a folder
  • and using ‘require or include’ in all our applications.

It all seems great then, but it will complicated and hard to manage our dependency between those third party packages. (For ex, version dependency between them to name a few). So, we will be using something called ‘Composer‘, a Dependency Manager thing. (I shoot a separate blog regarding your curiosity on why on using DM!)

Using Composer

    1. In a empty folder, named ‘API’, put a file called ‘composer.json’
    2. Download the ‘composer.phar’ file from http://getcomposer.org
    3. Add the below lines in ‘composer.json’

  1. As you guys can see, we have included ‘slim framework’ and a ODM for Mongodb’
  2. Now, all you need to do is ‘php composer.phar install‘ from terminal, it will install everything in a folder called ‘vendor’
  3. The last lines “autoload” is um… lil complicated to explain now (unless you heard about ‘namespaces and psr-o thing‘, not to worry, i tell ya soon).

(Pss, don’t forget, you must have installed Mongo and PHP-Mongo in your sys)

Deciding The Resource URL

Now, since its an RESTful application, all you have todo is to define the URLs for accesing particular resource. We need a URL for

  • Saving a blog     –   http://our-crazy-application/app/index.php/blog/add – POST
  • Retrieving our blog – http://our-crazy-application/app/index.php/blogs – GET

Eventhough, you can name URL anyway you can and ease any HTTP Method, its really ugly if you don’t follow the rules(sometimes!)

Time To Code… [/app/index.php]

1. Include ‘autoload’, which includes our Slim Framework & Mongo thing!

2. Now, we create the stuff when a POST data arrives

Now try to submit a form or use POSTMAN Rest Client to checkout the response.

Simple few lines to save your data and retrieve it, our REST Application is almost ready! Browse the code to get more clear idea about this https://github.com/sk8terboi87/simple-restful-tutorial-api/blob/blogs.

That’s it for now. In our next finally tut, we will see how AngularJs and our REST application successfully communicates and becomes a healthy application!!!

Updated:

Proceed to the Final Part:  http://code-like-a-poem.blogspot.in/2013/08/angularjs-tutorial-6-pt-3-building.html

References:

  1. http://stackoverflow.com/questions/90451/why-would-one-use-rest-instead-of-web-services
  2. http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
  3. http://en.wikipedia.org/wiki/Representational_state_transfer
  4. http://www.ibm.com/developerworks/webservices/library/ws-RESTservices/
  5. http://en.wikipedia.org/wiki/Clean_URL

AngularJs Tutorial 6 — Pt 1 — Building a RESTful Application With PHP & MongoDB – Part 1

Its been seriously very long time and I been drifting away too far from coding stuffs! (I should blame that someone, but, seriously its a waste of time, I realized this late)

Anyways, Not too long ago we were talking about http://code-like-a-poem.blogspot.in/2013/06/how-to-decide-right-restful-api-server.html! Finally, I spent my entire Saturday on this stuff!!

So, What are the things we gonna see…

  • Updated structuring for AngularJS
  • Making an RESTFUL API Call
  • Use of AngularJs Resource

The example tutorial is simple ‘yet another blog’ stuff, now we are only going to see how to make the API call only and nothing else. (need to go slowly)

Structuring

Sometime ago, we have learned how to automate stuffs with the help of Yeoman and GruntJs. But, in growing application, we need to properly place certain files in certain places so we can jump to files easily(With the help of Sublime Of course!).

I really hate seeing a high experienced people still use window browser and a mice to open a file. shessh!

Also, since we all know in AngularJs, we can create an entire application in one js file (with all controllers, factories in file), it does become messy soon!

So, we first make a proper flow and then jump to real coding thing!!

(Note: Below structure is not a official one, i just created myself which seems… nicer and understandable)

bootstrap.js Its the actual ‘app.js’ we previously know it. I prefer this name since it ‘kick starts’ the application. Also, if u see this file, it only initialize the module and place of injecting other modules in it.

Configuration/

routes.js- All the routes goes here!

constants.js – This is the place for declaring ‘application constants’, which can be later injected into our application just like injecting a service or factory.

Collections

It has sub collection of particular module or collection(hence!) of we what we gonna to do.

Ex., blogs, users, categories… etc.,

Also, we are gonna keep blogs related ‘Model’, ‘Controller’, ‘Factories’ in it itself.

(Model – Its actually a AngularJs services and we using its a pass-through for API calls and initializing stuff. Since it seems more neat by making calls from model instead of directly making it from the controller)

Services

Here, we will use our custom wrote services and directives for the same, just like collections

Components

These are all third party scripts, including angularjs scripts, etc. (We install these via Bower)

Making an RESTFUL API Call

1. Creating the controller

[..coffee/Collections/BlogsCollection/create.coffee]

As you can see, we are creating a controller called ‘BlogsController‘ and injecting out module ‘restfulTut‘ in it.

  1. Inside the controller, we injecting $scope and BlogsModel (a service)
  2. Then, We are calling ‘BlogsModel.initialize()‘. we just invokes the services for setting up any scope initialization variables, like, pre declaring stuffs or clearing it.
    1. The use of this is to move all the predeclaring stuffs out of the controller, so later when we see or debug our code, we can clearly focus on the ‘actual’ controller logic to the service.
  3. Finally, we created ‘$scope.save = ->‘ which will be invoked when ‘save’ is triggered from UI page
    1. This in-turn, triggers the ‘BlogsModel.send(‘add’, $scope.blog)
    2. $scope.blog contains the actual values which we need to post into API
    3. Also, later, we can perform validation logic here!

That’s all there is in controller to make a successfully call. Now, lets see what our Model does.

[..coffee/Collections/BlogsCollection/model.coffee]

As you can see,

  1. apiRoutes has the actually API URL, we just need to declare all our API urls here.
  2. Currently, initializeFn(), just initiate the scope.blog. You will feel the real usage when your application grows
  3. sendFn() – with the help angular resource, we are making the actually POST call here!
    1. resourceURL+ apiRoutes[route] – http://192.168.0.2/rest-api/app/index.php/ (We are injecting resourceURL from contants.js then here, we are appending the rest of the url

That’s all fellas, if you have tried submitting the form, it will make a POST request to the server. Of course it wont work, we still gotta write the API section which we will see in the next tut!

 A little about Angular Resource,

  • In order to make an ajax request to server side, you can either use $http or $resource.
  • With $resource, there are lot of options to modify the request call. (also, with the help of javascript of defer and two-binding, you can easily update the view on receiving a callback). You’ll get it later on the upcoming tut.

Phew! You will get more clear idea when you browse the code https://github.com/sk8terboi87/simple-restful-tutorial-ui/tree/blogs

Upcoming Tut:

  • Using Slim framework
  • Use of Dependecy Manager – Composer
  • Using an ODM for connecting MongoDB (and saving it ofcourse!)

Jump to part two: http://code-like-a-poem.blogspot.com/2013/08/angularjs-tutorial-6-building-restful_11.html

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/

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