Sharing data between two controllers in angularjs - javascript

Inside homeController file I have function
$scope.MyFunction = function () {
$http({
method: 'POST',
url: '/SomeUrl/ActionToDo',
data: { id: 1001 },
}).success(function (response) {
if (response.Status == 1) {
//success to do
}
$modal.open({
controller: 'modalController',
templateUrl: '/app/views/modalTemplate.html',
resolve: {
myData: function () {
return response;
}
}
});
} else {
alert(error);
}
}).error(function () {
alert('Error!');
});
}
Where I'm calling modalController to open modal window. Question is how can I pass data to this controller (modalController) from homeController in order to inject currently selected language which is available inside homeController in variable $scope.selLanguage

You can inject it into controller as resolve dependency:
$modal.open({
controller: 'modalController',
templateUrl: '/app/views/modalTemplate.html',
resolve: {
myData: function () {
return response;
},
language: $scope.selLanguage
}
});
so it will be available in controller as service
.controller('modalController', function(myData, language) {
console.log(language);
})

passed the data as locals to the modal controller using resolve.
resolve: {
myData: function () {
return response;
},
modalVar: $scope.selLanguage
}
In modalController refer that variable as it is local to that modalController controller.
angular.module('demo').controller('modalController', function ($scope, $modalInstance, modalVar) {
$scope.modalVar= modalVar;
});
Please refer this for more

Related

How to call php file via factory/service method using Angular.js

I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);

Access data from one controller to another controller- AngularJS

addressbookController :
$http({
method: 'GET',
url: '/api/getnewgroup'
})
.then(function (response) {
$scope.draft.groups = response.data;
$scope.groups = response.data; // updated
}, function (response) {
console.log(response);
});
In this above controller, i am getting json response in $scope.draft.groups, I have this draft object in another controller called profsmsController.
profsmsController :
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
How to access $scope object ?
My Controller:
angular
.module('sampleApp.controllers', [])
//addressbook page controller
.controller('addressbookCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window, sharedService) {
// Groups
// get group
$http({
method: 'GET',
url: '/api/getnewgroup'
})
sharedService.getDraftPromise().then(function (response) {
$scope.groups = response.data;
$scope.draft.groups = response.data;
}, function (response) {
console.log('error');
});
})
.controller('profsmsCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window) {
/* for drafts */
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
//add draft
$scope.addmanualInputDraft = function () {
$http.post('/api/addmanualinputdraft', $scope.draft).then(function (response) {
toastr.success("Added successfully!");
$('.bd-example-modal-lg-manual').modal('hide');
$state.reload();
});
}
})
My services.js:
angular
.module('sampleApp.services', [])
.factory('sharedService', function ($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function () {
return draftPromise;
}
};
});
my app.js:
'use strict';
angular
.module('sampleApp', ['sampleApp.controllers', 'sampleApp.directives','sampleApp.services','sampleApp.filters','ui.router','toastr','ngSanitize', 'ui.select'])
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/dash');
$stateProvider
.state('dash', {
url: '/dash',
templateUrl: 'partials/dash',
})
.state('quicksms', {
url: '/quicksms',
templateUrl: 'partials/quicksms',
controller: 'quicksmsCtrl'
})
.state('professionalsms', {
url: '/professionalsms',
templateUrl: 'partials/professionalsms',
controller: 'profsmsCtrl'
})
.state('file2sms', {
url: '/file2sms',
templateUrl: 'partials/file2sms',
controller: 'file2smsCtrl'
})
.state('addressbook', {
url: '/addressbook',
templateUrl: 'partials/addressbook',
controller: 'addressbookCtrl'
})
});
This is updated full code. I want to access $scope.draft.groups object from addressbook Controller.
In general, you'd want to create a service that holds your shared data:
myApp.factory('sharedService', function($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function() {
return draftPromise;
}
};
});
In your controllers, you can then use the service by declaring it as a dependency:
myApp.controller("myController", function($scope, sharedService) {
sharedService.getDraftPromise().then(function(response) {
$scope.draft.groups = response.data;
});
});
Both controllers will refer to the same instance of draftPromise.
Note: if you are minifying your code, you'll want to use the alternate syntax for dependency injection that uses arrays. Take a look at the official documentation for dependency injection.

Start several Functions by chain

I've got factory with some return on open modal window
Example:
openModal: function (urn, id, templateId, controller) {
$http({
method: 'GET',
url: urn
}).success(function (data, $scope) {
$("#" + id).append($compile(data)($scope));
modalInstance = $uibModal.open({
templateUrl: templateId,
controller: controller,
backdrop: 'static',
keyboard: false
});
}).error(function () {
alert("error");
return null;
});
document.getElementById('main').classList.add("blur");
},
After this function and view append to DOM, I want to call another function
from another service witch i inject to thouse openModalfactory.
Example:
$map.autocomplite('wizardsearch');
$map.getAutoUserLocationPath();
Could you explain how I must do this through $q?
Thank you for you answer.
deferring should make the function return a promise which you can use to do something when this function is finished
look to the the following code
openModal: function (urn, id, templateId, controller,$q) {
var def = $q.defer();
$http({
method: 'GET',
url: urn
}).success(function (data, $scope) {
def.resolve(data);
$("#" + id).append($compile(data)($scope));
modalInstance = $uibModal.open({
templateUrl: templateId,
controller: controller,
backdrop: 'static',
keyboard: false
});
}).error(function (err) {
def.reject(err)
alert("error");
});
document.getElementById('main').classList.add("blur");
return def.promise;
}
to use it call it like :
openModel().then(function(){
//do what you want here
})
I imagine that you want something like this :
let deferred = this.$q.defer();
let promises = [];
promises.push(service.something);
this.$q.all(promises).then(/*Do something*/);
return deferred.promise;

The right way to call http for every route AngularJs

I really new with AngularJs and I'm trying to create multiple routes with different $http requests. My problem start when the route change and the page content show later.
I figure it out in some way and i think its not the right way.
Hope someone can tell me if there is a better way.
Note: AngularJs version: 1.6 | Using ui router
main.js
var asTwl = angular.module('asTwl', ['ui.router']);
asTwl.controller('generals', function($scope, $http, $timeout){
$scope.pageLoader = false;
$scope.getPageData = function(path, postData, obj){
$scope.pageLoader = true;
$http({
method: 'post',
url: path,
data: postData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function(response) {
if (response.data) {
$scope.data[obj] = JSON.parse(response.data);
$timeout(function(){
$scope.pageLoader = false;
}, 100)
}
})
.catch(function(e) {
new Error('Error: ', e);
throw e;
})
}
});
asTwl.controller('homePage', function($scope, $http){
var postData = {
//data...
}
$scope.getPageData('path', postData, 'home')
})
asTwl.controller('singlePage', function($scope, $http, $stateParams){
var postData = $stateParams;
$scope.getPageData('path', postData, 'page')
})
asTwl.controller('categoryPage', function($scope, $http, $stateParams){
var postData = $stateParams;
$scope.getPageData('path', postData, 'category')
})
asTwl.config(function($stateProvider, $urlRouterProvider, $locationProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl : 'templates/pages/home.html',
controller : 'homePage'
})
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage'
})
.state('category', {
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
});
Thank you!
First, wrap your $http calls to services. Next,try to use resolve https://github.com/angular-ui/ui-router/wiki#resolve
Edit
Ok, example is here (without wrapping to service):
$stateProvider
.state('home', {
url: '/',
templateUrl : 'templates/pages/home.html',
controller : 'homePage',
resolve: {
routeData: function($http){
return $http({
method: 'post',
url: 'path',
data: postData /* your POST data - i don't know what is it for your code*/,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
}
})
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage'
})
.state('category', {
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
And in controller:
asTwl.controller('homePage', function($scope, routeData){
$scope.someData = routeData;
})
You should first create a service which will be responsible for communicating with Server/API for playing around with data. You could include that method getPageData in that, it returns a promise object.
Service
app.service('myService', function($http){
var self = this;
self.getPageData = function(path, postData){
return $http.post(path,postData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' });
.catch(function(e) {
new Error('Error: ', e);
throw e;
});
});
Then you could easily utilize the resolve option of state of ui-router will wait till your ajax promise gets resolved.
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage',
resolve: {
getData: function(myService) {
return myService.getPageData('path', {}, 'info')
}
}
})
In a nutshell your routes have to be changed like this:
.state('category', {
resolve: {
data : ($stateParams, dataService) => dataService.getData('path', $stateParams, 'category')
},
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
And getData method should be refactored to the service (dataService)

AngularJS: Performing $http request inside custom service and returning data

I have defined a custom http service in angular that looks like this:
angular.module('myApp')
.factory('myhttpserv', function ($http) {
var url = "http://my.ip.address/"
var http = {
async: function (webService) {
var promise = $http.get(url + webService, { cache: true }).then(function (response) {
return response.data;
});
return promise;
}
};
return http;
});
And I can access this service in my controller like so:
angular.module('myApp')
.controller('myCtrl', function (myhttpserv) {
var webService = 'getUser?u=3'
myhttpserv.async(webService).then(function (data) {
console.log(data);
})
});
However I now need to streamline this process so that it is ALL contained inside the service with a static url and it simply returns the data. So that I can just call it in the controller like so:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.var1);
console.log(myhttpserv.var2);
etc...
});
I can't seem to tweak the service to get this functionality. Anyone know the correct way to do it?
Option 1 - Use promise API
angular.module('myApp').factory('myhttpserv', function ($http) {
return $http.get('http://my.ip.address/getUser?u=3', { cache: true });
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, myhttpserv) {
myhttpserv.then(function(response){
console.log(response.data);
});
});
Option 2 - Using route resolve
angular.module('myApp', ['ngRoute']).config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/myCtrl', {
templateUrl: 'myView.html',
controller: 'myCtrl',
resolve: {
load: function (myhttpserv) {
return myhttpserv;
}
});
}]);
Service:
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.data.var1);
console.log(myhttpserv.data.var1);
etc...
});
Option 3 - Use $interval service
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, $interval, myhttpserv) {
$scope.intervalPromise = $interval(function(){
if (Object.keys(myhttpserv.data).length!=0)
{
console.log(myhttpserv.data);
$interval.cancel($scope.intervalPromise);
}
}, 100);
});

Categories