angularjs getting data from a url - javascript

I want to get json data from the url and assign it to a variable. I use a service that looks like this
app.service('dataService', function($http) {
this.getdata = function(callbackFunc) {
$http({
method: 'GET',
url: '/records/json/',
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
and my controller looks like this
app.controller('ReCtrl', ['$scope', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
But I get error TypeError: Cannot read property 'getdata' of undefined. I dont know what i am doing wrong. I appreciate any help.

You are not injecting your service (dataService) into your controller:
app.controller('ReCtrl',
['$scope', 'dataService', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
Note the extra string 'dataService' after '$scope' while defining the controller ReCtrl.

Related

How to get id from $http.get in angular.js

Hi I am a newbie and learning angular.js. I want to get data from this url which is actually an API (http://ba.dev/businesses/businesspage/36) but i dont know how can i Write this thing in my controller.js file. Given is my code please explain me how can I get the data from the business having id=36.
var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
$http.get('http://ba.dev/businesses/businesses').success(function(data){
$scope.business = data;
});
}]);
reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
$http.get('http://ba.dev/businesses/businesspage').success(function(data){
$scope.student = data;
$scope.whichItem = $routeParams.itemId;
});
}]);
Here is my app.js file
var myApp = angular.module('myApp',[
'ngRoute',
'reControllers'
]);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl : 'partials/main.html',
controller : 'RecentController'
}).
when('/page/:itemId',{
templateUrl : 'partials/page.html',
controller : 'PageController'
}).
otherwise({
redirectTo: '/main'
});
}]);
You can get the id from URL using $routeParams
$http.get('http://ba.dev/businesses/businesspage/'+ $routeParams.itemId)
Thereafter add server side logic, get passed itemId from URL, perform needful operation for getting data from DB and return it back.
You should use then instead of success, because it is deprecated. So, your code should be: `
$http.get('http://ba.dev/businesses/businesses').then(function(data){
$scope.business = data;
}); }]);.....
From AngularJS documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
More info about route params: AngularJS $routeParams

Angular not displaying $scope data with ng repeat passed in controller. No errors too

In this project, I am executing a query on click list item of ionic. I am getting the data from php json_encode. The data is getting displayed in the networks tab under response. Also, I have added $scope.doctorList = {}; and after that wrote this line $scope.doctorList = response which comes from success function. The data is getting displayed in console.log($scope.doctorList) as well.
Now when I try to display this data in angular, it does not show anything.
I have included it in ng-repeat as : ng-repeat = "doctors in doctorList"
The syntax seems to be correct as the same thing is working for another controller but here, I can't retrieve the data. The page goes blank and there is no error in console / netowrks tab.
I am using one controller for two html files. Please help
Here is the routes file
angular.module('app.routes', []).config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider.state('homeselect', {
url: '/home-select',
templateUrl: 'templates/homeselect.html',
controller: 'homeCtrl'
});
$stateProvider.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
});
});
Here is the controller
angular.module('app.controllers', []).controller('homeCtrl', function ($scope, $http, $ionicSideMenuDelegate, myServices, $window) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function (type) {
$http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: type
}
}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
});
};
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_details.php'}).success(function (data) {
$scope.contents = {};
$scope.contents = data;
});
});
Here is the html file code for ng-repeat
<ion-list ng-repeat="doctors in doctorList">
<ion-item>
<center>
{{doctors.name}}<br>
{{doctors.fees}}
</center>
</ion-item>
</ion-list>
You can use service.Open a file called service.js.After that this inject to app.js. I revised the code as follows:
Service.js:
angular.module('app.services', [])
.factory("AppService", function ($http) {
var AppService= {};
AppService.GetDetails = function (data) {
return $http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: data
}
});
return AppService;
}
controller.js:
.controller('homeCtrl',function($scope,$http,$ionicSideMenuDelegate,myServices,$window,AppService) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function(type){
AppService.GetDetails({type:type}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
})
.error(function (err) {
console.log(err);
});
}
});
ng-repeat iterates through a collection of items, create its own scope and renders it on UI. When I say collections, it should be an array.
https://docs.angularjs.org/api/ng/directive/ngRepeat
Please check the data-type for doctorList, which I believe is an array.
$scope.doctorList = [];
I hope this should solve the problem, if not please share the code I'll take a deep look into it.

AngularJs call controller function from factory

I'm trying a sample with angularJs where I'm trying to call a factory method and in the factory method, I'm doing an ajax callback to get result from database and in the success event of the ajax callback, I need to call a function in the controller to bind the result to the UI.
My Angular Code:
angular.module('myApp.controllers', [])
.controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
function($scope, $rootScope, $routeParams, Task) {
debugger;
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
});
$rootScope.UserMobileNumber = $routeParams.MobileNumber;
$scope.BindTasksList = function(resultData) {
debugger;
$scope.Tasks = resultData;
$scope.$apply();
}
}
]);
My Angular Factory Code:
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
debugger;
$.ajax({
url: '/api/TasksAPI/GetTasksList',
type: 'GET',
datatype: 'json',
data: {
'MobileNumber': MobileNumber,
'ClientCode': ClientCode
},
success: function(response) {
debugger;
$scope.BindTasksList(response);
},
error: function(xhr) {}
});
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function() {
return {
query: function(data) {
debugger;
GetTasks(data.MobileNumber, data.ClientCode);
}
}
}
]);
}());
My app.js Code:
'use strict';
angular.module('myApp', [
'ngTouch',
'ngRoute',
'ngAnimate',
'myApp.controllers',
'myApp.DbScripts'
]).
config(['$routeProvider',
function($routeProvider) {
debugger;
$routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
templateUrl: 'partials/tasks-list.html',
controller: 'TasksListCtrl'
});
$routeProvider.when('/tasks/:taskId', {
templateUrl: 'partials/task-details.html',
controller: 'TaskDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/status', {
templateUrl: 'partials/task-completion-details.html',
controller: 'TaskCompletionDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/route', {
templateUrl: 'partials/route-details.html',
controller: 'RouteDetailCtrl'
});
$routeProvider.otherwise({
redirectTo: '/tasks'
});
}
]);
But, I'm unable to call the function in controller. I've also tried it with angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response). But even that's not working.
Can anyone please point out the mistake I'm doing?
How to send the $scope of the controller to the factory?
You can do this by leveraging the $http promises, in you factory, return the promise instead as follows
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function($http) {
return {
query: function(data) {
return $http({
url: '/api/TasksAPI/GetTasksList',
method: 'GET',
params: {
'MobileNumber': data.MobileNumber,
'ClientCode': data.ClientCode
}
}).then(function(result) {
return result;
});
}
}
}
]);
}());
Then in your controller you can access the $http response object that is returned:
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
}).then(function(resp) {
// access $http resp here and attach to $scope.Tasks
});
If you can, I would advocate using $q along $http as well, so that you do not need to parse through the http response and get a nice little response data object back
plnk

Angular ajax failed using $http

I got an error TypeError: Cannot read property 'success' of undefined when using $http and my custom service.
My app.js :
app.controller('AppCtrl', ['$scope', '$http', 'topicContent', function($scope, $http, topicContent){
topicContent.request().success(function(data){
$scope.threadContent = data;
console.log(data);
});
}]);
app.factory('topicContent', ['$http', function($http){
var query = function() {
return
$http({
url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
method: "GET"
});
}
return {
request : function(){
return query();
}
}
}]);
This is so strange, I couldn't find any flaw of it.
The problem is that this code
var query = function() {
return
$http({
url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
method: "GET"
});
}
is equivalent to this one:
var query = function() {
return;
$http({
url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
method: "GET"
});
}
due to automatic semicolon insertion in javascript. Note that there is semicolon ; after return. So the solution is to move $http to the same line after return statement:
return $http({ ... });
Read about in what situations javascript interpreter inserts semicolon ; automatically, for example here. In your case after return interpreter will insert ; which makes query function return undefined. Hence the error you are getting.

How to get json data in my case?

I am trying to use httml get to get the json
I have something like
.controller('testController', function($scope, $state, $http) {
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
console.log(data)
});
//outside of the $http scope but under the same controller, I have
//It shows undefined.
console.log($scope.testData)
})
I know we have to keep data our of the login codes so I don't want to modify the data inside the $http. Is there anyway to accomplish this? Thanks!
First, don't put this in a controller. Move it to a Service. That's what Services are designed for.
Second, the $http service is asynchronous. Your result only exists in the success callback, and your console.log will be called before the http request is finished. You need to assign it to a scope variable to use it outside of the callback, and expect it to be empty until the call back is complete.
http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app provides an example of an AngularJS authentication service, if that's what you're doing.
To go with your example:
.controller('testController', function($scope, $state, $http) {
$scope.testData = {};
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
$scope.logData();
});
$scope.logData = function() {
console.log($scope.testData);
}
});
This plnkr code is created in order to give your answer, yes you can have the $scope.testData outside the http request.
Have a look!!
var app = angular.module('plunker', []);
app.controller('testController', function($scope, $http) {
$http({
url: "test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
alert(data);
callA();
});
function callA(){
alert($scope.testData);
}
});

Categories

Resources