Monday, 6 June 2016

Create a custom factory in Angular Js

In this post we are going to see how to create a Factory in angular js. Factory is a alternate way of creating objects once we create a Factory, we can use it in the controllers or in the another Factory through dependency injection.

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

app.factory('DBFactory'function () {

    return {
        ConnectionString: function () {
            return "DataSource=;Username=rajesh;Password=Pass12#";
        GetData: function () {
            return [{ name: 'Rajesh', Id: 1 }, { name: 'Ramu', Id: 2 }];


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

    $scope.Title = "Sample Angular Application";  
    $scope.Fstring = DBFactory.ConnectionString();


    <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 />
            <br />
            <span> Connection String from Factory: {{Fstring}} </span>          

No comments:

Post a Comment