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 ,
function(data)
{
//Getting data from myServicefunction(factory)
$scope.datalist = data ;// response from service
},
function( data)
{
//error
});
};
});
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="list.data">
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 ,
somedata :data.data
};
var url = 'your webservcie url';
//Sending to service ( backend )
$http.post( url, angular.toJson(data) )
.success( function( data )
{
//Getting data from backend
success(data);
//Send back to controller
})
.error( function( data)
{
error(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
No comments :
Post a Comment