I am trying to pass the value from controller to another using $rootscope what I did is first I intialize rootScope like this
app.run(function ($rootScope) {
$rootScope.emp=0 ;
});
then I am changing the value of rootScope in one of my controller like this this
app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
$scope.update = function (data) {
alert(data);
$scope.message = $http.post('http://localhost:5000/api/employee/view', data).
then(function (response) {
$scope.userEdit = response.data;
$rootScope.emp=$scope.userEdit[0].id;
alert($rootScope.emp);
});
window.location.href = "updateEmployee.html";
};
});
then i am trying to access this changed $rootScope.emp value in my second controller but getting the value that i set at the time of initialization which is 0
app.controller("UpdateController", function ($scope, $http, $rootScope) {
$scope.userid=$rootScope.emp;
alert($scope.userid);
});
Try This :
app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
$scope.update = function (data) {
alert(data);
$scope.message = $http.post('http://localhost:5000/api/employee/view', data).
then(function (response) {
$scope.userEdit = response.data;
$rootScope.$apply(function(){
$rootScope.emp=$scope.userEdit[0].id;
});
alert($rootScope.emp);
});
window.location.href = "updateEmployee.html";
};
});
Detailed Answer can be found here
Related
I try to use a service to get some data from server, but I had a problem: even the console log out the length when I print 'myData.length', when I try to find length of '$scope.test' controller variable it tell me that it is undefined.
What I should to do to use a $http service inside my own service?
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test;
console.log('$scope.test = ' + $scope.test.length);
}]);
app.factory('mapServ', ['$http', function ($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path).then(function (response) {
myData = response.data;
console.log(myData.length);
});
return out;
}]);
Take these service and controller as an example and you should follow John Papa's style guide while writing the code.
Service
(function() {
'use strict';
angular
.module('appName')
.factory('appAjaxSvc', appAjaxSvc);
appAjaxSvc.$inject = ['$http', '$q'];
/* #ngInject */
function appAjaxSvc($http, $q) {
return {
getData:function (path){
//Create a promise using promise library
var deferred = $q.defer();
$http({
method: 'GET',
url: "file path to my server data"
}).
success(function(data, status, headers,config){
deferred.resolve(data);
}).
error(function(data, status, headers,config){
deferred.reject(status);
});
return deferred.promise;
},
};
}
})();
Controller
(function() {
angular
.module('appName')
.controller('appCtrl', appCtrl);
appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];
/* #ngInject */
function appCtrl($scope, $stateParams, appAjaxSvc) {
var vm = this;
vm.title = 'appCtrl';
activate();
////////////////
function activate() {
appAjaxSvc.getData().then(function(response) {
//do something
}, function(error) {
alert(error)
});
}
}
})();
In your code you do not wait that $http has finished.
$http is an asynchronous call
You should do it like this
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test.then(function(response) {
console.log(response.data);
}, function(error) {
//handle error
});;
}
]);
app.factory('mapServ', ['$http', function($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path);
return out;
}]);
$http call that you are making from factory is asynchronous so it will not wait , until response come, it will move on to the next execution of the script, that is the problem only try Weedoze's asnwer, it is correct way to do this.
I have two factories in my angular app.
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
var userId = UserService.getUser().userID;
$http.get('http://myurl.com/something/'+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
And I have a value I get from another factory :
var userId = UserService.getUser().userID;
But I doesn't update when the UserService.getUser() is changed, the view changes with $watch, but I don't know how it work inside a factory.
Any help is welcome, thanks guys !
Anyone ?
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id='+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
I simply need to make userId variable dynamic..
A better design pattern will be this
app.factory('UserService',
['$http', function($http) {
var getUser = function() {
return http.get("url_to_get_user");
};
return {
getUser: getUser
};
}]);
app.factory('ArtistService',
['$http', '$q', 'UserService', function($http, $q, UserService) {
var getFavoriteArtists = function() {
UserService.getUser().then(function(response) {
var userId = response.data.userID;
return $http.get('http://myurl.com/something/' + userId);
}, function() {
//passing a promise for error too
return $q.reject("Error fetching user");
});
};
return {
getFavoriteArtists: getFavoriteArtists
};
}]);
Now call it in controller like,
ArtistService.getFavoriteArtists().then(function(response) {
//do something with response.data
}, function(response) {
//log error and alert the end user
});
How can i assign the response to a variable or $scope. Here i want to assign the response to data variable
here is the screen shot
'use strict';
`var dashModule = angular.module("Student");`
dashModule.controller("studentDashboardCtrl",
['$scope', 'authService', 'StudentService',
function ($scope, authService, StudentService) {
//Check authorised user
var data;
authService.checAuthentication();
StudentService.getBatchList(function (response) {
console.log(response);
});
}]);
You can store it in $scope variable,
$scope.value=response;
var dashModule = angular.module("Student");
dashModule.controller("studentDashboardCtrl",
['$scope', 'authService', 'StudentService',
function ($scope, authService, StudentService) {
//Check authorised user
var data =[];
authService.checAuthentication();
StudentService.getBatchList(function (response) {
console.log(response);
data.push.response; //just like that you can store the response
});
}]);
Actually i am checking the result using console.log(); But it always shows undefined. though my approach was right. I am still confused why console.log() shows undefined. But the view shows the value correctly. Here's the code
'use strict';
var dashModule = angular.module("Student");
dashModule.controller("studentDashboardCtrl",
['$scope', 'authService', 'StudentService',
function ($scope, authService, StudentService) {
//Check authorised user
var names;
authService.checAuthentication();
StudentService.getBatchList(function (response) {
$scope.names = response;
});
console.log($scope.names);
}]);
You Should Use this.
$Scope.myvariable = response;
var Module = angular.module("Student");
dashModule.controller("studentDashboardCtrl",
['$scope', 'authService', 'StudentService',
function ($scope, authService, StudentService) {
//Check authorised user
var self = this;
authService.checAuthentication();
StudentService.getBatchList(function (response) {
console.log(response);
self.data = response.data;
});
}]);
I have a factory, calling the service and getting the response and passing in to the controller and trying to store the response in a variable which is getting undefined
app.factory('Myservice', function (service1, service2) {
return {
getService: function (data) {
service1("user", encodeURIComponent("pass")).then(function (response) {
varSessionData = response.Obj;
var queryString = strURL[1].split("&");
Service2.pageLoad(SessionData).then(function (response) {
var homeScreen = response;
data(homeScreen);
});
});
}
};
});
In Controller:
var Mydata = MyService.geService(function (data) {
Console.log(data);
return data; // getting response
});
$scope.Hello = Mydata; // undefined
Whenever you make any AJAX request they are asynchronous. That is why Angular promises are used (the .then method). So you should change your code like this in your controller:
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
});
Change it to the following, your data isn't defined synchronously.
Controller:
MyService.geService(function(data) {
$scope.Hello = data;
});
i have pass the $scope.Hello in Another Service controller,which means depend upon that taking the result from services.
Not working?
var HomeController = function ($scope, $rootScope, $http, $stateParams, $state, Service3, Myservice)
{
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
});
Not working
Service3.pageLoad($scope.Hello) // not get the value
.then(function (response) {
$scope.ServiceModelobj = response;
console.log(response);
}
Working code
var HomeController = function ($scope, $rootScope, $http, $stateParams, $state, Service3, Myservice)
{
MyService.geService(function (data) {
Console.log(data);
$scope.Hello = data;
Working//
Service3.pageLoad($scope.Hello) // get the value
.then(function (response) {
$scope.ServiceModelobj = response;
console.log(response);
});
}
}
I want to retrieve data from an $http.get and put it in $rootScope :
.run
app.run(function ($rootScope, $q, $http, $timeout, stateRules) {
stateRules
.then(function (data) {
$rootScope.user = data;
console.log(data);
});
});
.service
app.service('stateRules', ['$http','$q', function($http, $q) {
var userUrl= 'api/user/';
var userService = {};
var deferred = $q.defer();
$http.get(userUrl+ "getUserName", { cache: true }).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
});
.controller
app.controller('userCtrl', ['$scope', function ( $scope) {
console.log($scope.user);
}]);
but the value of the $scope.user in my controller is undefined. Any idea how to fix it ?
Thanks
$rootScope should be injected in a service. like this.
.service('ServiceGetSVC', ['$http','$rootScope','$q',function ($http,$rootScope,$q) {....}
Or if you try to use $rootScope.user after method get. It was undefined becouse method get asynchronous. Should use deferred.
in application
ServiceGetSVC.then(data){
$rootScope.user = data;
}
service
.service('stateRules', ['$http','$q' function($http, $q) {
var deferred = $q.defer();
$http.get(communUrl + "getUserName", { cache: true }).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}])