Thursday 27 February 2014

Communication between factory file and controller in Angular js

Controller is a JavaScript constructor function that is used to augment the Angular scope. It is communicating with views and factory files and also with directives ,filter etc . Factory files are interacting with backend services through REST API and usually communicating with specific controls (how to set up a single page application using Angular)

Controller example

Here SampleController is the controller name and samplefactoryService is the factory file name

angular.module('sampleproject').controller( 'SampleController',
function ($rootScope, $scope ,samplefactoryService )
$scope.list = {
 value : '',
 data : '' 
$scope.onSample = function()
//Sending data ($scope.list ) to myServicefunction (factory)
 samplefactoryService.myServicefunction( $scope.list ,
//Getting data from myServicefunction(factory)
 $scope.datalist = data ;// response from service
 function( data)

Here $scope.list is nothig but you can take value from view .For example in view you have a input box

 <input ng-model="list.value"> 
 <input ng-model=""> 

You can have this values in controller by using $scope.list . You can initialize onSample function on ngclick or by form submission .

 <button ng-click="onSample();"> Submit </button>

Here we are sending our data ($scope.list) to myServicefunction in samplefactoryService. So we have to create a samplefactoryservice.js and have to declare myServicefunction.

Example of Factory File in angular

'use strict';
angular.module('harbinger').factory( 'samplefactoryservice',
function( $rootScope, $http)
return {
//data($scope.list) from controller
myServicefunction : function( data  )
 var data = {
   value:data.value ,
 var url = 'your webservcie url';
 //Sending to service ( backend )
 $ url, angular.toJson(data) )
 .success( function( data )
//Getting data from backend


 //Send back to controller
 .error( function( data)
yourotherfunction : etc .....

Here we are getting $scope.list value from the controller file and sending to service file .On success we are getting the response from service file (backend).

Related Posts

1. Communicate with controllers in angular js

2. Rating Stars using angular js Directive concept

3. Angular routing

No comments :

Post a Comment