AngularJS how to assign response data to a variable - angularjs

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;
});
}]);

Related

Passing rootScope value from one controller to another controller

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

Using $http inside my own service - variable does not persist

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.

Running factory based on condition

I have a log in screen that when the user enters the correct credentials will be able to get JSON data. For now I don't have a real API link. I'm just using dummy JSON data from a script file. The loginCtrl will pass parameters to the 'dummydata' factory which will make a 'GET' request. On success, the factor will pass the JSON data to the 'useData' function in the factory. This function in the factory is what all the controllers in my ng-view use.
The problem that I am having is that all the other controllers are calling 'dummyData.dashboardsData' and getting undefined because no one has logged in to pass data to that function. How can I prevent controllers (for example, navCtrl) from calling the factory until someone has logged in?
This is my index file:
<body ng-app="ciscoImaDashboardApp" ng-style="{'background-image': backgroundImg}" ng-controller="loginCtrl">
<login></login>
<div ng-view></div>
<menu></menu>
</body>
This is my factory:
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.login = function(user,password,callback) {
$http({method: 'GET', url: 'scripts/services/dummydata.js'})
.success(function (response) {
dataStatus = response.success;
apiServices.useData(response);
callback(dataStatus);
})
.error(function(error) {
console.log("There was an error: " + error);
});
};
apiServices.useData = function(response) {
var data = response.data;
apiServices.dashboardsData = data;
}
return apiServices;
}]);
This is my navCtrl:
angular.module('ciscoImaDashboardApp')
.controller('navCtrl', function($scope, navService, $location, dummyData) {
var data = dummyData.dashboardsData;
});
This is my loginCtrl:
angular.module('ciscoImaDashboardApp')
.controller('loginCtrl', function ($scope, $rootScope, dummyData, $location) {
$scope.login = function() {
var user_email = $scope.email;
var user_password = $scope.password;
dummyData.login(user_email, user_password, function (dataStatus) {
if (dataStatus) {
console.log("Success!");
$scope.loggedIn = true;
$location.path('/welcome');
} else {
console.log("Error");
}
});
}
});

Pass authentication error from factory to controller in AngularJS

I am trying to implement Firebase authentication via a factory and I would like to pass the error and even the authData object back to the controller from the factory. Is this possible? I can't seem to figure out how. I keep getting undefined variables.
If I print the error upon a failed login to console.log I get what should be expected, so the rest of this code works. I just can't pass the error/obj back to the controller.
My controller:
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user);
// do something with error from auth factory
}
}]);
My factory:
myApp.factory('Authentication', ['$firebase', 'FIREBASE_URL', '$location', function($firebase, FIREBASE_URL, $location){
var ref = new Firebase(FIREBASE_URL);
var authObj = {
login: function(user) {
return ref.authWithPassword({
email : user.email,
password : user.password
}, function(error, authData) {
if (error) {
// pass error back to controller
// i've tried the following:
// authObj.err = error;
// return authObj.err = error;
}
else {
// pass authData back to controller
}
});
} // login
};
return authObj;
}]);
You simply pass an error handler function to the factory from the controller. Something like this (untested):
//Controller
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user, function(error, authData) {
// access to error
});
}
}]);
//Factory
myApp.factory('Authentication', ['$firebase', 'FIREBASE_URL', '$location', function($firebase, FIREBASE_URL, $location){
var ref = new Firebase(FIREBASE_URL);
var authObj = {
login: function(user, errorHandler) {
return ref.authWithPassword({
email : user.email,
password : user.password
}, errorHandler);
} // login
};
return authObj;
}]);
Maybe you can do this in your controller:
$scope.login = function() {
Authentication.login(username, password).then(
function(result) {
$location.path('/stuff');
},
function(result) {
$scope.showLoginErrorMessage = true;
});
};
Note that then() takes 2 functions as parameters (one for success and one for error). This does depend on how your Authentication service works, but it looks OK to me.

Angular - function inside .factory

I'm trying to run a function inside .factory to get posts, but I get an undefined error on my controller.
.factory('Portfolio', function($http, $log) {
//get jsonp
this.getPosts = function($scope) {
$http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
.success(function(result) {
$scope.posts = $scope.posts.concat(result);
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
});
.controller('PortfolioCtrl', function($scope, Portfolio) {
$scope.posts = [];
Portfolio.getPosts($scope);
Thanks!
What you wrote is a service not a factory. so you either
change it to be .service instead of .factory.
or return the function inside an object like this
.factory('Portfolio', function($http, $log) {
//get jsonp
return {
getPosts: function($scope) {
$http.jsonp()
.success(function(result) {
$scope.posts = $scope.posts.concat(result);
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
}
});
check the difference between service and factory
Use .factory code like this
.factory('Portfolio', function($http, $log) {
//get jsonp
return{
getPosts: function($scope) {
$http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
.success(function(result) {
$scope.posts = $scope.posts.concat(result);
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
}
});

Resources