Saturday, January 9, 2016

AngularJS – Controllers

Controllers in AngularJS exists to augment the views of an AnuglarJS applications. The controller in AngularJS is a function that functionality to the scope of the view. We use it to set up the initial state and to add custom behavior to the scope object.

When we create the controller on a page, Angular passes it a new $scope. This new $scope is where we can set up the initial state of the scope on our controller. Since Angular takes care of handling the controller for us, we only need to write the constructor function.
Setting up the initial controller looks like this:

function FirstController($scope) {
    $scope.message = “Hello”;
}

Doing so is usually poor form, as we don’t want to dirty the global namespace. To create it more properly, we’ll create a module and then create the controller on top of our module, like so:

var app = angular.module(‘app’, []);
app.controller(‘FirstController’, function($scope) {
    $scope.message = “Hello”;
}

To create custom actions we can call in our views, we can simply create functions on the scope of the controller. Luckily for us, AngularJs allows our views to call functions on the $scope, just as if we were calling the data.

To bind buttons or links (or any DOM element, really), we’ll use another built-in directive, ng-click.
The ng-click directive binds the mouseup browser click event to the method handler, which calls
the method specified on the DOM element (i.e., when the browser fires a click event on the DOM
element, the method is called). Similar to our previous example, the binding looks like:

<div ng-controller="FirstController">
<h4>The simplest adding machine ever</h4>
<button ng-click="add(1)" class="button">Add</button>
<a ng-click="subtract(1)" class="button alert">Subtract</a>
<h4>Current count: {{ counter }}</h4>
</div>

Both the button and the link are bound to an action on the containing $scope, so when they are
pressed (clicked), Angular calls the method. Note that when we tell Angular what method to call,
we’re putting it in a string with the parentheses (add(1)).
Now, let’s create an action on our FirstController.

app.controller('FirstController', function($scope) {
    $scope.counter = 0;
    $scope.add = function(amount) { $scope.counter += amount; };
    $scope.subtract = function(amount) { $scope.counter -= amount; };
});


Setting our FirstController in this manner allows us to call add or subtract functions (as we’ve
seen above) that are defined on the FirstController scope or a containing parent $scope.
Using controllers allows us to contain the logic of a single view in a single container. It’s good
practice to keep slim controllers. One way that we as AngularJS developers can do so is by using the
dependency injection feature of AngularJS to access services

AngularJS – Scopes

The $scope object is where we create the business functionality of the application, methods in our controllers, and properties in the views. Scopes serve as the glue between the controller and the view.
Scopes provide the ability to watch for the model changes. They give the developer the ability to propagate the model changes throughout the application by using the apply mechanism available on the scope.

It is ideal to contain the application logic in controller and model working data on the scope of the controller.

When Angular starts to run and generates the view, it will create a binding from the root ng-app element to the $rootScope. This scope is the eventually parent of all the $scope objects. The $rootScope object is the closest object we have to the global context in the Angular app. It’s a bad idea to attach too much logic to this global context, in the similar way that it’s not a good idea to dirty the JavaScript global scope.

Scopes have the following basic functions:
  •          They provide observers to watch for model changes.
  •         They provide the ability to propagate model changes through the applications as well as outside the systems to other components.
  •         They can be nested such that they can isolate functionality and model properties.
  •         They provide an execution environment in which expressions are evaluated.

    Example



Output

In the above example notice that the Mycontroller assigns the value “Jatin” to the username property on the scope. The Scope then notifies the input of the assignment, which then renders the input with the username pre-filled. This demonstrates how controller can write data to the scope.

Similarly the controller can assign behavior to the scope as seen by the sayHello method, which is involved when the user clicks on the ‘greet’ button. The sayHello method reads the username property and creates the greeting property. This demonstrates that the properties on scope update automatically when they are bound to the HTML input widgets.

 


AngularJS – Module

In Angular, a module is the main way to define an AngularJS app. The module of an app is where we’ll contain all of our application code. An app can contain several modules, each one containing code that pertains to specific functionality. You can think of a module as container for the different parts of your app – controllers, services, filters, directives etc.

Modules provide us a lot of advantages, such as
  •        Keeping our global namespace clean.
  •         Making testing easier as independent modules can be tested separately.
  •         Making it easy to share code between applications.
  •          Allowing our app to load different parts of code in any order.


The angular modules API allows us to declare a module using the angular.module() method.
When declaring a module, we need to pass two parameters to the method. First is the module name and second one is the list of Dependencies also known as injectable.

angular.module(‘moduleName’, []);

However we can also use the overloaded method with single parameter as shown below,

angular.module(‘ModuleName,);

Example


In following example we going to create two modules
  •          Application Module – used to initialize an application with controllers.
  •         Controller Module – used to define a controller.
MyApp.js

Var app  =  angular.module(“myApp”, []);

MyController.js

App.Controller(“myController”, function($scope) {
                $scope.firstName = “Jatin”;
                $scope.lastName = “Patil”;
});

AngularJSModule.html

 


Output


AngularJS - Introduction

AngularJS is the client-side technology, written entirely in JavaScript. It works with the long-established technologies of the web (HTML, CSS and JavaScript) to make the development of web apps easier and faster than even before.

AngularJS extends HTML with new attributes. It is a framework that is primarily used to build single-page web applications. AngularJS makes it incredibly easy to build web applications; it also makes easy to build complex applications.

Features
  •  Separation of application logic, data models and view
  •  Ajax Services
  • Dependency Injections
  •  Browser history ( makes bookmarking and back/forward buttons work like normal web apps )
  • Testing
  •  Cross browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • And more…

Data binding and First AngularJS Web Application


Data binding is one of the most basic and impressive features of the AngularJS. Many classic Web frameworks combine data form the model and mashes them together with templates to deliver a view to the user. This combination produces a single way view, the view only reflect the data the model exposes at the time of the view rendering.

AngularJS takes different approach. Instead of merging the data in to the template and replacing a DOM element, AngularJS creates a live template as a view. Automatic data binding gives us the ability to consider the view to be a projection of the model state. Any time the model is changed in the client-side model, the view reflects these changes without writing any custom code.

Hello World example



Output



In above example we have just included angular.js in our HTML and explicitly setting the ng-app attribute on an element in the DOM. The ng-app attribute declares everything inside of it belongs to the Angular app; that’s how we can nest an Angular app inside of a web app. The only components that will be affected by the Angular are the DOM elements that we declare inside of the one with the ng-app attribute. Views are interpolated when the view is evaluated with one or more variable substitutions; the results is that the variables in our string are replaced with the values. For instance, if there is variable named name and it is equal to “Jatin”, string interpolation on a view of “Hello { { name } }” will return “Hello Jatin”.