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=233.44.1.3;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();
});
<html>
<head>
<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>
</head>
<body>
<div ng-app="app">
<div ng-controller="main">
<h1>{{Title}}</h1>
<br />
<br />
<span> Connection String from Factory: {{Fstring}} </span>
</div>
</div>
</body>
</html>
No comments:
Post a Comment