Access data from one controller to another controller- AngularJS - javascript

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.

Related

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 get data after add item with http post without refresh using mdDialog

For add new user I use dialog using Angular Material (mdDialog), but now I must to refresh page to get new data added.
To get user I use this code in AdminController:
var init = function() {
$http({
method: 'GET',
url: 'http://localhost/hrm/public/getUsers'
}).success(function(data) {
angular.forEach(data, function(item) {
console.log(item);
$scope.users.push(item);
});
}).error(function (data) {
console.log(data);
});
};
init();
To add a user I use this code in AdminController:
$scope.addUser = function(event) {
$mdDialog.show({
controller: DialogController,
parent: angular.element(document.body),
templateUrl: 'views/admin/addUser.html',
controllerAs: 'ctrl',
clickOutsideToClose: true,
targetEvent: event
}).then(function(addUser) {
$mdToast.show(
$mdToast.simple()
.textContent("User ajouté avec succès")
.position('top right')
.hideDelay(1500)
);
}, function(cancel) {
});
};
And addUser I added this function in DialogController:
$scope.addUser = function() {
if($scope.password == $scope.cpassword) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/saveUser',
data: {email: $scope.email,password: $scope.password}
}).success(function(data) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/assign-role',
data: {email: $scope.email, name: $scope.selectedItem}
}).success(function(data) {
$scope.users.push(data);
console.log(data);
});
});
} else {
console.log("password error");
}
$mdDialog.hide();
};
I get this error:
TypeError: Cannot read property 'push' of undefined
I think because I put $scope.users = [] in AdminController, and not have access in DialogController.
So how can I use $scope.users in both controllers?
There is a lot of why to do it, like mention in comments $rootScope or locals or $emit or $broadcast or $watch
So i resolved with locals property of $mdDialog, so in $scope.addUser in AdminController i do like this
$scope.addUser = function (event) {
$mdDialog.show({
controller: DialogController,
parent: angular.element(document.body),
templateUrl: 'views/admin/addUser.html',
controllerAs: 'ctrl',
locals: {
items: $scope.users
},
clickOutsideToClose:true,
targetEvent: event
}).then(function (addUser) {
$mdToast.show(
$mdToast.simple()
.textContent("User ajouté avec succès")
.position('top right')
.hideDelay(1500)
);
}, function(cancel) {
});
};
and in add function
$scope.addUser = function () {
if($scope.password == $scope.cpassword){
$http({
method: 'POST',
url: 'http://localhost/hrm/public/saveUser',
data: {email: $scope.email,password: $scope.password}
}).success(function (data) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/assign-role',
data: {email: $scope.email, name: $scope.selectedItem}
}).success(function (data) {
items.push(data);
});
});
}
else {
console.log("password error");
}
$mdDialog.hide();
};
and must the items pass in controller function .

Sharing data between two controllers in angularjs

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

Web API call failed in Device mode

I have implemented the small mobile application in Cordova (VS2015). In my application I'm getting all the required data using asp.net wep api. My mobile solution working fine in ripple emulator. But not working in device mode (Andorid). I have published my web service and local IIS server and I use local IP address and port no to access it. Also I have enable cross domain call in my web api too.
bellow is my app.js find and service That I have implement using angularJS.
var app = angular.module('RandBApp', ['ionic', 'RandBApp.controllers'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($compileProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|ghttps?|ms-appx|x-wmapp0):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|ms-appx|x-wmapp0):|data:image\//);
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "app/views/menu.html",
controller: 'RandBAppCtrl'
})
.state('app.products', {
url: "/products",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/products.html",
controller: 'ProductsCtrl'
}
}
})
.state('app.productdetail', {
url: "/products/:productid",
views: {
'menuContent': {
templateUrl: "app/views/productdetail.html",
controller: 'ProductDetailCtrl'
}
}
})
.state('app.signup', {
url: "/signup",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/signup.html",
controller: 'SignUpCtrl'
}
}
})
.state('app.reservations', {
url: "/reservations",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/reservations.html",
controller: 'ReservationsCtrl'
}
}
})
.state('app.reservationdetail', {
url: "/reservations/:reservationid",
views: {
'menuContent': {
templateUrl: "app/views/reservationdetail.html",
controller: 'ReservationDetailCtrl'
}
}
})
.state('app.orders', {
url: "/orders",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/orders.html",
controller: 'OrdersCtrl'
}
}
})
.state('app.orderdetail', {
url: "/orders/:orderid",
views: {
'menuContent': {
templateUrl: "app/views/orderdetail.html",
controller: 'OrderDetailCtrl'
}
}
})
.state('app.loyaltyhistory', {
url: "/loyaltyhistory",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/loyaltyhistory.html",
controller: 'LoyaltyHistoryCtrl'
}
}
})
.state('app.notifications', {
url: "/notifications",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/notifications.html",
controller: 'NotificationsCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/products');
});
var serviceUrl = 'http://localhost:6787/';
app.constant('ngAuthSettings', {
apiServiceBaseUri: serviceUrl,
clientId: 'ngAuthApp',
loginCredentail: 'loginCredentail'
});
Here is my Service
app.factory('loyaltyservice', ['$http', '$q', '$log', 'ngAuthSettings', function ($http, $q, $log, ngAuthSettings) {
var loyaltyFactory = {};
var webAPIbase = ngAuthSettings.apiServiceBaseUri;
var loginCredentailKey = ngAuthSettings.loginCredentail;
var getLoyaltyTransactionDetails = function (userId) {
var deferred = $q.defer();
$http({
method: 'GET',
url: webAPIbase + "api/Loyalty/GetLoyaltyTransactionDetails",
params: {
userId: userId
}
}).success(function (response) {
deferred.resolve(response);
}).error(function (err, status, header, config) {
deferred.reject(err);
});
return deferred.promise;
};
loyaltyFactory.getLoyaltyTransactionDetails = getLoyaltyTransactionDetails;
return loyaltyFactory;
}]);
Any Help really appreciate.
Sorry Guys. I forgot to enable to port in firewall. After enabaling it is started to work.

how can i pass id to my ui-view

I want to access inventory by id, using link /inventory/description/:{{id}} But it isnt working, nothing shows up. how can i access it by id ?
app.config(function config( $stateProvider, $urlRouterProvider) {
$stateProvider.state('inventory',{
url:'/inventory',
views: {
"main": {
controller: 'InventoryCtrl',
templateUrl: 'inventory/main.tpl.html'
}
},
data:{ pageTitle: 'Inventory' }
}
).state('inventory.detailview',{
url:'/inventory/detailview',
views: {
"detailview": {
controller: 'InventoryCtrl',
templateUrl: 'inventory/detail.tpl.html'
}
},
data:{ pageTitle: 'DetailView' }
}
).state('inventory.description',{
url:'/inventory/description/:{{id}}',
views: {
"descriptionview": {
templateUrl: 'inventory/description.tpl.html',
controller: function($scope, Inventory){
$scope.id = Inventory.query('id');
}}
},
data:{ pageTitle: 'DescriptionView'}
});
});
my factory
app.factory('Inventory', function($resource, $http) {
return $resource('http://web.lv/api/v1/inventory/:id', {id: "#id"},
{
update: {
method: 'POST',
params: {id: '#id'},
isArray: false
},
save: {
method: 'PUT'
},
query: {
method: 'GET',
params: {id: '#id'},
isArray: false
},
create: {
method: 'POST'
},
drop: {
method: 'DELETE',
params: {id: "#id"}
}
}
);
});
my controller
app.controller('InventoryCtrl', function($scope, $http, Inventory, $location) {
//getting the objects from Inventory
$scope.info = Inventory.query();
//
$scope.id = Inventory.query('id');
}
If you are using ui-router, you can use stateParams
app.controller('InventoryCtrl', function($scope,$stateParams,Inventory) {
$scope.id = $stateParams.id;
}

Categories