Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, December 5, 2015

Creating Services in Angular2.0

In an application,  service is a component which consists of business logic or set of individual functions. Services often served as loosely coupled modules.

If you are building an Angular2.0 application there are various ways to inject the service into your component. Service consumption in Angular2.0 application follows dependency injection principles. Component can be resembled to directives in Angular1.x. So if you component needs a service instance, then the service can be injected while constructing the component.

For example here I am creating a component named as Event component, following is the way the component can be accessed in HTML:


<event-component></event-component>

The Angular2.0 code for the above component written below:

@Component({

    selector: 'event-component',
    templateUrl:'eventcomp.html',
    styles: [],
    directives: []

})

class EventComponent {

  constructor(VenueService:VenueService,

  @Inject('App.config')config: config,food:FoodAndBeveragesService) {

    this.title=config.title;
    this.schedule=config.schedule;
    this.duration=config.duration;
    this.venueServiceInst=VenueService;
    this.booked=false;
    this.beveragesIncluded=food.beveragesIncluded;

  }

  bookVenue(){

    if(this.venueServiceInst.bookVenue()){
      this.booked=true;
    }
  }
}

The constructor in the above code has three services injected into it.


  • VenueService
  • FoodAndBeveragesService
  • config

While bootstrap of your component you can configure services for your component, as written below:


bootstrap(EventComponent,[VenueService,FoodAndBeveragesServiceProvider,
provide('App.config', {useValue:config})]);

The VenueService code is pretty simple, following is the code:


import {Injectable} from 'angular2/angular2';
@Injectable()
export class VenueService{
  bookVenue(){
    console.log('booking venue');
    return true;
  }
}


The above service is written in a separate typescript file. So the export notifies which class you want to expose for access from other files. The Injectable annotation says that the service is injectable.

The FoodAndBeveragesService code is as simple as above service, following is the code:


import {Injectable} from 'angular2/angular2';

@Injectable()
export class FoodAndBeveragesService{

beveragesIncluded:boolean;
  constructor(beveragesIncluded?:boolean){
  this.beveragesIncluded=beveragesIncluded; 
  }

  bookFoodAndBeverages(){

    return true;
  }
}

But while injecting there is a provider configured for it, to create a provider for the service, here is the code snippet for it:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService();
};

let foodAndBeveragesServiceDefinition = {
   useFactory: foodAndBeveragesServiceFactory,
   deps:[]
};

let FoodAndBeveragesServiceProvider = provide(FoodAndBeveragesService, foodAndBeveragesServiceDefinition);
The contrasting difference between the  injection of VenueService and FoodAndBeverageService is the creation of the service instance is in the control of it's corresponding factory method, so in the above factory creation we can change the invocation of the service instance creation as shown in the following code:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService(beveragesIncluded);
};
Now lets come to config service, this is how it's been created:

let config = {

  title: 'AngularJS Meetup',

  schedule:'Mon, 23rd Dec 2015',

  duration:'6'

};
So config is basically an object which can be injected in to any component. To inject it as it's written in the bootstraping of the component:

provide('App.config', {useValue:config})
And while injecting it in the constructor of the component we mention it as follows:

@Inject('App.config')config: config

So above are the ways to create and inject services in Angular2.0. Following is the working code base of the above examples.

Saturday, November 21, 2015

Creating a video player using Angular 2.0

The best way to learn Angular2.0 is to write components. So instead of writing tutorial I prefer to start creating components. In this post we will create a video player having custom control to show the usage of Angular2.0

Typescript and SystemJS are two dependencies requires for this example.

Please install Angular2.0 as mentioned in the below link:

https://angular.io/docs/ts/latest/quickstart.html

The following plunkr contains the codebase  for the component:

The full-screen feature might not work because of browser's restriction. However once you copy the codebase to your favorite editor and run it, the full-screen feature will work smoothly. All Functionalities have been tested in Safari, Chrome and Firefox browser.

Please fell free to comment on the component so that I can extend it to have more functionalities.






Sunday, February 22, 2015

AngularJS controller in-depth

Controller in an AngularJS application plays as a role of bridge between your model and view. There are certain best practices need to be followed while designing a controller for your application.

  • REST calls should not be invoked in controller(Use Services).
  • Any filtering of the data like changing the text as browser language changes should not be done in controller(Use Filters)
  • Controllers should not be used to act as a communicator between two different AngularJS modules(Use event emitters)

Following example shows how to write a controller("Controller as" Syntax):

HTML file


<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="testapp">
      <div ng-controller="utilcontroller as util">
        <input type="text" ng-model="util.name">
        <button ng-click="util.greeting()">Say Hii</button>
        <div>
          <b>{{util.nameWithGreetingMsg}}</b>
        </div>

      </div>

    </div>
  </body>

Javascript file(script.js mentioned in the HTML file)


angular.module("testapp", []).controller('utilcontroller', function() {

    this.greeting = function() {
   
    this.nameWithGreetingMsg = "Hello " + this.name;
  }
});


Constructor is a constructor function, in the above example utilcontroller  is the constructor function, so when we mention the ng-controller directive in the HTML, this constructor function get called and a new object gets created. In the above example the new object name is util.

Let's write without "controller as" syntax.

HTML file

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div ng-app="testapp">
    <div ng-controller="utilcontroller">
      <input type="text" ng-model="name">
      <button ng-click="greeting()">Say Hii</button>
      <div>
        <b>{{nameWithGreetingMsg}}</b>
      </div>

    </div>

  </div>
</body>
</html>

Javascript file(script.js mentioned in the HTML file)


angular.module("testapp", []).controller('utilcontroller', function($scope) {

  $scope.greeting = function() {

    $scope.nameWithGreetingMsg = "Hello " + $scope.name;
  }

});

In the above program all the properties and methods are attached to $scope.


Scope Inheritance

To achieve scope inheritance controllers can be used. It's very normal while creating an HTML view we assign different controllers at different view level. so for example in the below program:

<div ng-controller="vehiclecontroller as vehicle">
  <div ng-controller="carcontroller as car">
    No of wheels: <b>{{car.wheels}}</b>
    <button ng-click="vehicle.start()">Start Car</button>
  </div>
  <div ng-controller="bikecontroller as bike">
    No of wheels: <b>{{bike.wheels}}</b>
    <button ng-click="vehicle.start()">Start Bike</button>
  </div>
</div>

We have one parent controller and two child controllers,  the child controller are able to access the parent scope's data through referring the parent controller's name(vehicle.start). The 'start' method is defined in vehiclecontroller function:

angular.module("testapp", []).controller('vehiclecontroller', function() {
  
  this.start = function() {

    console.log("vehicle started");
  }

}).controller('carcontroller', function() {
  this.wheels = 4;
}).controller('bikecontroller', function() {
  this.wheels = 2;
});

$watch in controller

$watch is AngularJS is used to observe the scope properties, once the property's value  changes the callback function defined in the $watch executes.

Inside controller we write watchers(in case of controller as syntax):

controller('carcontroller', function($scope) {
  this.wheels = 4;
  this.gear="neutral";
  $scope.$watch(angular.bind(this,function(){return this.gear}),function(newVal,oldVal){
    console.log("Gear changed from"+ oldVal+ "to "+newVal);
  });


Note: More about angular.bind.


In case of without controller as syntax the $watch is pretty simple:
 $scope.$watch('gear',function(newVal,oldVal){
    console.log("Gear changed from"+ oldVal+ "to "+newVal);
  });


That's pretty much for controller's role inAngularJS app. In the upcoming post we will learn about FormController role in an application.



Sunday, July 27, 2014

Key points about AngularJS Directive and custom element using Polymer.

Creating custom element is achievable by creating a custom Directive in AngularJS. We can say it's one of the best feature of the framework. As Google's Polymer project is in hype for it's material design and web component based architecture, it also supports functionalities to create a custom component.

To create a directive in AngularJS:


To create a custom web component in Google Polymer:


Once you get a understanding both of these ways to develop a component we may conclude these are main key points to achieve each blocks of custom component:


Functionality In AngularJS In Polymer
Template of a custom element It supports writing template as well as loading template from a URL It supports writing template
Styling template and it's contents In template itself you can add styles and classes In template you can have "<style>" tags to describe different inline styling
Wrapping other HTML by custom component It provides ng-transclude as well as trancluseFunction to achieve this functionality Here it provides insertion point, which tells the browser where to render children
Writing JavaScript logic It can be written inside controller, compile and lining functions. It can be written inside "<script>" tag.


























Sunday, June 29, 2014

key binding on auto suggestion list in AngularJS




Following are the work flow steps:

1: Enter a value in the first text field
2: The suggestion list appears below the text box.
3: Up and Down key are used to navigate between items in the list.
   Selected item appears in gray color.
4: Press Enter key to select an item from the list.
5: Press tab to move to second field.
6: You can also use mouse to select one item from the list

Sunday, June 15, 2014

ng:repeat and radio button problems

We all know ng-repeat creates it's own scope for each repeated item. Take the following example

<html>
<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];

    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <div ng-repeat="item in nameList">{{item.name}}</div>
</body>
</html>



The above code actually creates two divs (one for each item in the nameList) and renders those with the content and the output would be
Lemon
John

If we try to do similar thing where we put radio buttons instead of divs it will create separate scope for each radio button.

Let's change our HTML to the below one:


<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="selectedItem">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>

Here is the Plunkr link:

Plunkr for above HTML

However if we select any radio button it does not change the selectedItem value of the scope, because it changes value of selectedItem of the new scope for span, to bind to the parent scope's selectedItem object we have to change the code to....

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="$parent.selectedItem">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>


The $parent refers to the parent scope so now we refer to the selectedItem object which is defined in our controller.

The above approach looks simple, however when the radio button goes under a transcluded directive  we need to refer something like $parent.$parent....... till we reach the main controller's scope.

Another approach would be doing this in event publish/subscribe pattern.
Here is the implementation:


<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope, $rootScope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];

      $scope.changehappened = function(data) {

        $rootScope.$emit('nameselected', data);
      };
      $rootScope.$on('nameselected', function(evt, data) {

        $scope.selectedItem = data;
      });
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="$parent.s" ng-change="$parent.changehappened(item)">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>