Sunday, 5 June 2016

Create a Custom Provider in Angular Js

In this post  we are going to see how to create a provider in angular js, Provider is some what different from the Service and Factory, Because Provider can only be inject into the config section. 

Provider must return a custom property $get, where this will further return a Factory function. After create a Provider we have to inject in to module in the config phase along with some suffix name Provider with the name.

Normally where we can use this provider is settings which need to be set at config phase like Database connection sting or some other settings.

var app = angular.module('app', []);

app.provider('Database'function () {
    var prop = {
        ConnectionString: ""

    return {
        setConnectionString: function (data) {
            prop.ConnectionString = data;
        $get: function () {
            return ({
                ConnectionString: function () {
                    return (prop.ConnectionString);


app.config(function (DatabaseProvider) {

app.controller('main'function ($scope, Database) {

    $scope.Title = "Sample Angular Application";   
    $scope.providerString = Database.ConnectionString();

}); (Database) {

    <script src="scripts/angular.min.js" type="text/javascript"></script>
    <script src="scripts/angular-route.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <div ng-app="app">
        <div ng-controller="main">
            <br />           
            <span>Connection string from Provider : {{providerString}} </span>

From this post you can learn how to create a provider in angular js.

No comments:

Post a Comment