Here are my code -
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
return result.data;
});
console.log($scope.artists);
}]);
How to view the original data from json file?
Move the assignment statement inside the success block:
.success(function(result) {
$scope.artists = result.data;
})
Also, one more thing to note is the console.log($scope.artists) statement right after the $http block will still print undefined because it is executed before the promise is resolved.
Try this it will work :
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
$scope.artists = result.data;
}).error(function(msg) {
$scope.err = msg;
});
}]);
Related
How do i pass data from the controller to a component to show to the user?
app.js
(function(angular) {
'use strict';
angular.module('app', []).controller('MainCtrl', function MainCtrl($scope, $http) {
$http({
method: 'GET',
url: '/team',
}).then(function successCallback(response) {
console.log(response.data);
this.teams = response.data;
$scope.teams = response.data;
// var keys = Object.keys($scope.agendaEventData);
// $scope.eventslength = keys.length;
}, function errorCallback(response) {
});
}).config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
})(window.angular);
component
(function(angular) {
'use strict';
angular.module('app').component('bringTeamToEvent', {
templateUrl: '/assets/ng/app/team/bringTeamToEvent.html',
bindings: {
teams: '<'
},
});
})(window.angular);
Template
{{$ctrl.teams}}
{{teams}}
The data is coming from the api no problems, i do not understand the complexity to get it to work.
Learning from https://docs.angularjs.org/tutorial/step_13
and https://docs.angularjs.org/guide/component#!
Setting the data on this.teams is correct, and correct to access it like $ctrl.teams. The issue here is that your $http callback functions are injecting their own function context so that this doesn't refer to the component.
For this reason, it's generally good practice to use arrow functions for callback functions:
$http({
method: 'GET',
url: '/team',
}).then(response => {
this.teams = response.data;
}, response => {
});
Here is a demo
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) {
});
};
}
]);
I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}
Here is my service:
app.service('trackService', ['$http', function($http) {
var data;
this.topTracks = function(limit) {
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks; console.log(this.data); return this.data;
});
}
}]);
and controller -
app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
$scope.data = trackService.topTracks(10);
//console.log($scope.data);
}]);
how to send data to the controlller using a $http service inside a custom service?
Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead
You need to return the promise from service and set the scope in a promise callback in controller
app.service('trackService', ['$http',
function($http) {
var data;
var self = this;
this.topTracks = function(limit) {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {
api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
format: 'json',
limit: limit
}
}).then(function(result) {
self.data = result.data.tracks;
console.log(self.data);
return self.data;
});
}
}
]);
app.controller('artistSongsCtrl', ['$scope', 'trackService',
function($scope, trackService) {
trackService.topTracks(10).then(function(data) {
$scope.data = data;
//console.log($scope.data);
});
}
]);
Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:
app.service('trackService', ['$http', '$q', function($http, $q) {
var data;
this.topTracks = function(limit) {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks;
console.log(this.data);
d.resolve(this.data);
});
return d.promise;
}
}]);
I want to inject my service into my controller and just see my console log (in the Auth Service), but I'm getting this error: Argument 'myAppController' is not a function, got undefined. What am I doing wrong?
In my main.js file I have:
var myApp = angular.module('myApp',['ngRoute', 'ui.router']);
myApp.controller('myAppController', ['$scope', function($scope, AuthService) {
console.log('controller');
AuthService.console();
...
In my services.js file I have:
var myApp = angular.module('myApp',[]);
myApp.service('AuthService', function(){
this.console = function(){
console.log('in the AuthService');
}
});
Loading the files in my index.html file as:
<script src="js/main.js"></script>
<script src="js/services.js"></script>
Gotta declare it as a string too for the injection:
myApp.controller('myAppController', ['$scope', 'AuthService', function($scope, AuthService) {
Define MyApp Like this
var myApp = angular.module("myApp", ['ngRoute', 'ui.router']);
myApp.controller('myAppController', function ($scope, ajaxService) {
ajaxService.ajaxGetWithData(url).then(function (data) {
$scope.Data= data;
});
});
app.service('ajaxService', function ($http, $q) {
this.ajaxGetWithData = function (url) {
var deferred = $q.defer();
$http({
method: 'POST', url: url, data: $.param(User),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
})
.success(function (data) {
if (data != null) {
deferred.resolve(data);
}
})
.error(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
});