You must know about angularjs

angularjs features angularjs two way binding angularjs one time binding angularjs watch angularjs watch collection how the watch works in angularjs angularjs http service angularjs http defer promise

Angularjs has many feature which makes developer life easier specially the way of binding and changing values when there is any change in value automatically. As an Angularjs developer, what are the features we must know before starting coding. Here are some of the features we will discuss in this article 1. Data Binding (one way, two way and one time data binding) 2.

Data Binding (one way, two way and one time data binding)

One of the amazing feature of Angularjs is the data binding. It is easy to bind and format the data. Most of the time we need one way of binding means just to show the data on the page. Let's see some simple one way binding and formatting:

// Say I have two values on my scope
$scope.userName = 'World';
$scope.someDate = new Date();
// In view (HTML)
<div> Hello {{userName}}</div>
<div>{{someDate | date :'MM/dd/yyyy'}}</div>
// Output
Hello World
10/14/2015

If you note we only use {{}} and put the variable name in it and done. If you note the someDate variable, it is formatted in a proper date format, similarly if you have a currecy value just say {{variable | currecy}} and it will put the $ sign before it, it not it simple.

In above example we used the hard coded value, but if we use services which is very obvious in any application, this binding will show {{variables}} until the value is retrieved from the database. So what is the solution or other way? I will suggest to use the ng-bind and ng-bind-template, here is the same code,

 <div ng-bind-template='Hello {{userName}}'></div>
 <div ng-bind="someDate | date :'MM/dd/yyyy'"></div>

In this way of binding, these div will be hidden until the value are assigned. There is another way if you want to explore ngCloak.

Two-way binding: Let's say you have bind a label and text box with the same variable, when you change the value in text box, label will automatically changed, use the above variables and test this

 <label ng-bind='userName'></label>
 <input type='text' ng-model='userName' />

When you will type anything in input, it will immediately show the same value in label, without writing a single line of JavaScript code.

One-time binding: An expression that starts with :: is considered a one-time expression. One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value.

<div>Hello {{::userName}}</div> 

Check angular expression for more detail

$watch:

Dirty checking can be done with three strategies: By reference, by collection contents, and by value. The strategies differ in the kinds of changes they detect, and in their performance characteristics.

Let's say we have a scope object users which we want to watch

 $scope.users = [
    { name: 'John', age: 22 },
    { name: 'Robert', age: 25 },
    { name: 'Jeffery', age: 30 }
  ];

Watching by reference: detects a change when the whole value returned by the watch expression switches to a new value. If the value is an array or an object, changes inside it are not detected. This is the most efficient strategy.

$scope.$watch('users', function(newval, oldval){
    if(newval != oldval)
        alert('changed');
});

// Somewhere in our code
$scope.users = null;
// This will call the watch because reference is changed;

If we will add a new user to the list or update any value will not call the watch method, for example

$scope.users.push({ name: 'Ali', age: 31 });
// Silently it will add the new user

$scope.users[0].age = 15;
// Silently it will change the value

Watching collection contents: detects changes that occur inside an array or an object: When items are added, removed, or reordered. The detection is shallow - it does not reach into nested collections. Let's check the above examples with it, here is our new watch collection

$scope.$watchCollection('users', function(newval, oldval){
    if(newval != oldval)
        alert('changed');
});
  • Called: on initialization, even at the very first time (on load)
  • Called: Reference is changed $scope.users = null;
  • Called: New record is added $scope.users.push({ name: 'Ali', age: 31 });
  • Not called: when value updated $scope.users[0].age = 15;

Watching by value: detects any change in an arbitrarily nested data structure. It is the most powerful change detection strategy, but also the most expensive. A full traversal of the nested data structure is needed on each digest, and a full copy of it needs to be held in memory.

It is very similar to the first one (by reference) with 3rd parameter value true, see this

$scope.$watch('users', function(newval, oldval){
    if(newval != oldval)
        alert('changed');
}, true);
  • No Called: on initialization, even at the very first time (on load)
  • Called: Reference is changed $scope.users = null;
  • Called: New record is added $scope.users.push({ name: 'Ali', age: 31 });
  • Called: when value updated $scope.users[0].age = 15;

alt text

$broadcast, $emit and $on: In some cases we need to pass the value from one controller to other controller, in this case we need to use these features. I hope you know the parent child scope and rootScope concept, if not please check Scope Hierarchies

  • $broadcast: dispatches an event downwards to all child scopes and their children. The even cannot be cancelled.
  • $emit: dispatches an event upwards through the scope hierarchy. The event will stop propagating if one of the listeners cancels it.
  • $on: listen an event by it's name on the scope

Let's say we have our HTML like this

<div ng-controller='Ctrl1'>
    <div ng-controller='Ctrl2'>
    </div>
</div>

If we need to pass some value from Ctrl1 to Ctrl2 then we will use $broadcast (downwards)

app.controller('Ctrl1', function($scope){
    $scope.$broadcast('someEvent', 'some value');
});
app.controller('Ctrl2', function($scope){
    $scope.$on('someEvent', function(event, data){
       console.log(data);
    });
});

In the same way if we want to pass some value from Ctrl2 to Ctrl1 then we will use $emit (upwards)

app.controller('Ctrl1', function($scope){
    $scope.$on('someEvent', function(event, data){
       console.log(data);
    });
});
app.controller('Ctrl2', function($scope){
    $scope.$emit('someEvent', 'some value');
});

Suppose if they are in parent child scope then how can we pass the value like this

<div ng-controller='MenuCtrl'>
</div>
<div ng-controller='Ctrl2'>
</div>

In this case we will use $rootScope to broadcast the value. It is a very genuine situation which we will face in real life application. I the top menu shows the user login status and name but the other controller say Login is maintaining the login information. Once the user is login or logout menu should be changed. Let's change our HTML to show in more logical example

<div ng-controller='MenuCtrl'>
    Welcome {{user.name}}
</div>        

<div ng-controller='LoginCtrl'>
    <button ng-click="login()">Login</button>
    <button ng-click="logout()">Logout</button>
</div>

I used two controllers, menu and login, login controller have two method login and logout which we call by button. Note we also need to pass the $rootScope as dependency to call any method on it.

app.controller('MenuCtrl', function($scope, $rootScope){
    $scope.user = {name: 'Guest'};
    $rootScope.$on('login', function(event, data){
       $scope.user = data;
    });
     $rootScope.$on('logout', function(event, data){
       $scope.user = data;
    });     
});
app.controller('LoginCtrl', function($scope, $rootScope){        
    $scope.login = function(){
      $rootScope.$broadcast('login', {name: 'Johan'});
    }

     $scope.logout = function(){
      $rootScope.$broadcast('logout', {name: 'Guest'});
    }
});

$http service

is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. To communicate with database we need to write WebAPI Services to select/insert/update data into database. These WebAPI methods will be called with the help of $http service. The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

Simple get request example

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

If you want to write the above code in simple way then it will be

$http.get('/someUrl').then(function success(response) {
    // Other code
  }, function error(response) {
    // other code
  });
Alicia Gonzalez I am working on .Net since last 7 years.C# is really amazing language and I like to learn everything about C# and want to share whatever I know.
  • angularjs
  • $http
  • $watch
By Alicia Gonzalez On 15 Oct, 15  Viewed: 386

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 4,796

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 23,146

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 9,770

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 1,667

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 18,295