Create a $http.get properly - javascript

I would like to create a $http.get service properly but I have trouble with services in AngularJS. I create this code and It works but all the code is in the controler :
var monApp = angular.module('monApp', []);
monApp .controller('PhoneListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('http://port:serveur/fichier.xml').then(function(response) {
var x2jObj = X2J.parseXml(response.data); //X2J.parseXml(xmlDocument, '/');
var tableauJSON = X2J.getJson(x2jObj);
}, function(a, b, c) {
alert("Impossible de télécharger le fichier");
});
}
]);
Can you help me to create it in service ?
Thanks.

create a service with name fichierService and a function getData like
monApp.factory("fichierService", function($http) {
return {
getData: function() {
return $http.get('http://port:serveur/fichier.xml');
}
}
});
and use that fichierService service in your PhoneListCtrl controller by inject
monApp .controller('PhoneListCtrl', ['$scope', '$http','fichierService',
function($scope, $http, fichierService) {
fichierService.getData().then(function(response) {
// rest of code
}, function(a, b, c) {
alert("Impossible de télécharger le fichier");
});
}
]);

monApp.service('myFooService', function() {
this.get = function (url) {
return $http.get(url).then(function(response) {
var x2jObj = X2J.parseXml(response.data);
var tableauJSON = X2J.getJson(x2jObj);
});
}
});
and then you can use your service like this
monApp.controller('fooCtrl', function($scope, myFooService) {
myFooService.get('http://foo.com/foo.xml');
});
This should give an idea on how to start implementing your own service.

This is the perfect solution, the controler :
var app = angular.module("myApp", []);
app.controller("MainCtrl", ["$scope", "userService",
function($scope, userService) {
userService.getData();
}
]);
The web service :
app.service("userService",["$http",
function($http) {
_this = this;
this.getData = function() {
$http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"};
$http.defaults.headers.common['Authorization'] = 'Basic ' + window.btoa('username' + ':' + 'password');
$http.get('http://YourServer:YourPort/rest/api/2/auditing/record').
success(function(data) {
console.log(data);
});
}
}
]);

Related

AngularJS: $routeParams to work within a service

I know this is easy, but I can't quite wrap my head around how to do this.
I need to do the API call within a service so that those variables can be accessed between two separate controllers.
The problem I am having is I can't access $routeParams (which I need for the get) within the service. I can't figure out know how to pass $routeParams from the controller to the service.
app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
var posts = function posts() {
$http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
console.log(JSON.stringify(res) );
});
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts
};
}]);
factory :
app.factory('Page', ['$http', function($http) {
var _posts = function posts(param) {
return $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts : _posts
};
}]);
Controller :
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
Page.posts($routeParams.slug).then(function success(response) {
$scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);
please note that success is deprecated in newer versions of Angular. I have updated the code with then

using a angularjs variable in a ajax request with a .load url

I am mostly a PHP coder and have VERY VERY limited dealing with jquery.
I am showing a banner ad based upon the end users' location. I'm using a AngularJS script to return the users zip code: http://jsfiddle.net/kL50yeek/21/
I'm using the follow ajax code to load the right banner ad based upon the zip provided:
<div id="adspaceNetwork_sponsored_bank"></div>
<script>
$('#adspaceNetwork_sponsored_bank').load("https://ia.lc/~creative/?
zip=02481");
</script>
You can see the code demo here: https://jsfiddle.net/cdLw0c48/22/
How do I pass the zipCode Var to the ajax load request?
This doesn't work: $('#adspaceNetwork_sponsored_bank').load('https://ia.lc/~creative/?zip='+zipCode);
I've update your jsfiddle here with angularjs bindings:
Here is your updated controller:
app.controller('MainCtrl', ['$scope', '$http', '$sce', 'ZipCodeLookupSvc',
function($scope, $http, $sce, ZipCodeLookupSvc) {
$scope.zipCode = null;
$scope.message = 'Finding zip code...';
ZipCodeLookupSvc.lookup().then(function(zipCode) {
$scope.zipCode = zipCode;
$http.get('https://ia.lc/~creative/?zip='+zipCode).success(function(res) {
$scope.banner = $sce.trustAsHtml(res);
});
}, function(err) {
$scope.message = err;
});
}]);
After we get the zipCode via ZipCodeLookupSvc, we use a $http.get call to fetch the banner, and set it as $scope.banner for use in your html code.
I updated your code and transferred the load call.
app.controller('MainCtrl', ['$scope', 'ZipCodeLookupSvc', function($scope, ZipCodeLookupSvc) {
$scope.zipCode = null;
$scope.message = 'Finding zip code...';
ZipCodeLookupSvc.lookup().then(function(zipCode) {
$scope.zipCode = zipCode;
$('#adspaceNetwork_sponsored_bank').load('https://ia.lc/~creative/?zip=' + zipCode);
}, function(err) {
$scope.message = err;
});
}]);
There are multiple problems in your handling of promises
(function (angular) {
'use strict';
var app = angular.module('MyApp', []);
app.factory('GeolocationSvc', ['$q', '$window', function ($q, $window) {
return function () {
var deferred = $q.defer();
if (!$window.navigator) {
deferred.reject(new Error('Geolocation is not supported'));
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
deferred.resolve({
lat: position.coords.latitude,
lng: position.coords.longitude
});
}, deferred.reject);
}
return deferred.promise;
};
}]);
app.factory('ZipCodeLookupSvc', ['$q', '$http', 'GeolocationSvc', function ($q, $http, GeolocationSvc) {
var MAPS_ENDPOINT = 'https://maps.google.com/maps/api/geocode/json?latlng={POSITION}&sensor=false';
return {
urlForLatLng: function (lat, lng) {
return MAPS_ENDPOINT.replace('{POSITION}', lat + ',' + lng);
},
lookupByLatLng: function (lat, lng) {
var deferred = $q.defer();
var url = this.urlForLatLng(lat, lng);
$http.get(url).success(function (response) {
// hacky
var zipCode;
angular.forEach(response.results, function (result) {
if (result.types[0] === 'postal_code') {
zipCode = result.address_components[0].short_name;
}
});
deferred.resolve(zipCode);
}).error(deferred.reject.bind(deferred));
return deferred.promise;
},
lookup: function () {
var deferred = $q.defer();
var self = this;
GeolocationSvc().then(function (position) {
self.lookupByLatLng(position.lat, position.lng).then(function (zipCode) {
console.log('p')
deferred.resolve(zipCode);
}, deferred.reject.bind(deferred))
}, deferred.reject.bind(deferred));
return deferred.promise;
}
};
}]);
app.controller('MainCtrl', ['$scope', 'ZipCodeLookupSvc', function ($scope, ZipCodeLookupSvc) {
$scope.zipCode = null;
$scope.message = 'Finding zip code...';
ZipCodeLookupSvc.lookup().then(function (zipCode) {
$scope.zipCode = zipCode;
console.log(zipCode)
$('#adspaceNetwork_sponsored_bank').load('https://ia.lc/~creative/?zip=' + $scope.zipCode);
}, function (err) {
$scope.message = err;
});
}]);
})(angular);
Demo: Fiddle

How to Redirect with MVC when calling $post in angular

So upfront, I am new to angular so I am a little lost with how I want to accomplish a redirect after I post data back to a server:
I have the following in a update:
$http.post("#Url.Action("SaveBranding", "AirlineConfig")", brandModel.model);
Then on the server I have this in my controller:
[HttpPost]
public ActionResult SaveBranding(BrandingViewModel viewModel)
{
if (IsModelStateValid())
{
var airline = GetAirlineFromAirlinePlatformId(viewModel.AirlinePlatformId);
switch (viewModel.PostAction)
{
case "Save":
BrandingViewModel.SaveEntity(viewModel, _db);
var airlineBranding = BrandingViewModel.FromEntity(_db.AirlinePlatforms.Single(x => x.AirlinePlatformId == viewModel.AirlinePlatformId).BrandingViews, viewModel.AirlinePlatformId);
return View("Branding", airlineBranding);
case "Save & Close":
BrandingViewModel.SaveEntity(viewModel, _db);
return RedirectToAction("Edit", "AirlineConfig", new { id = airline.AirlineId });
case "Cancel":
return RedirectToAction("Edit", "AirlineConfig", new { id = airline.AirlineId });
default:
return HttpNotFound();
}
}
return View("Branding"); //Replace this later
}
My routing isnt working and I am lost how to do this so I can navigate to the correct location.
Use window.location to manually redirect in the browser rather than use a server redirect.
The angular way to redirect is using $location service.
angular.module('someModule', [])
.controller('SomeController', ['$scope', '$http', '$location', someController])
function someController($http, $location) {
$scope.brandModel = {};
$scope.submit = function () {
$http.post("#Url.Action("SaveBranding", "AirlineConfig")", brandModel.model).then(function (data) {
$location.path('/url/to/path');
});
}
}
I put this answer here for completeness. I think also $location is more geared up for handling either hash urls or html5mode urls. If you use raw JavaScript, then you either use window.location.hash = "someUrl" or window.location.href = "someUrl". That could be a little caveat for not doing it the "angular" way.
I noticed also that you include that #Url.Action("", ""), when I did my Angular app with MVC in the index page I did this:
angular.module('someModule', [])
.factory('urlService', urlService)
function urlService() {
var service = {
getSaveBrandingUrl: getSaveBrandingUrl
};
return service;
function getSaveBrandingUrl() {
return '#Url.Action("", "")';
}
}
That way I can have all my other scripts separate, and they only rely on a function name so if you change the URL you don't have to go around the app changing all the links. When you inject this into the controller you would do something like:
angular.module('someModule', [])
.controller('SomeController', ['$scope', '$http', '$location', 'urlService', someController])
function someController($scope, $http, $location, urlService) {
$scope.brandModel = {};
$scope.submit = function () {
$http.post(urlService.getSaveBrandingUrl(), brandModel.model).then(function (data) {
$location.path('/url/to/path');
});
}
}
Obviously then you can tie all that up into it's own service to reduce the injection into the controller:
angular.module('someModule', [])
.factory('someControllerService', ['$http', 'urlService', someControllerService])
.controller('SomeController', ['$scope', '$location', 'someControllerService', someController])
function someController($scope, $location, someControllerService) {
$scope.brandModel = {};
$scope.submit = function () {
someControllerService.saveBranding($scope.brandModel.model).then(function (data) {
$location.path('some/url');
});
}
}
function someControllerService($http, urlService) {
var service = {
saveBranding: saveBranding
};
return service;
function saveBranding(branding) {
return $http.post(urlService.getSaveBrandingUrl(), brandModel.model).then(function (data) {
return data.data;
});
}
}

calling method from one controller to another controller in angular js

I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here

Angular.js - making function available in other controllers

I have an angular controller called SubmissionTreeController and it has update_dashboard() function which refreshes the ui every minute.
My goal is to refresh the ui on successful post request from a different controller.
How do I make this function available in other controllers?
var module = angular.module("submissionDashboard", ['ui.tree', 'ngCookies', 'ui.bootstrap',]);
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal",
function($scope, $http, $modal) {
$scope.selected_items = {};
var update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
update_dashboard();
$scope.closeTask = function(scope) {
var modalInstance = $modal.open({
templateUrl: 'modal_close_submission_renderer.html',
controller: 'ModalCloseSubmissionController',
resolve: {
items: function () {
return $scope.selected_items;
}}
});
};
}]);
module.controller('ModalCloseSubmissionController', ['$scope', '$modalInstance', '$http', 'items', function ($scope, $modalInstance, $http, items) {
$scope.items = items;
$scope.selected = {
item: 1,
text: ''
};
$scope.ok = function () {
var val = $scope.selected.item;
if (val === 1) {
var url = Django.url('submission:close-notify', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 2) {
var url = Django.url('submission:close', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 3) {
var url = Django.url('submission:cancel', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
};
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
Edit:
What I am trying to do:
module.service('updateDashboardService', function($scope, $http){
this.update_dashboard = function() {
$scope = $scope;
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
});
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal", "updateDashboardService", function($scope, $http, $modal, updateDashboardService) {
$scope.selected_items = {};
updateDashboardService.update_dashboard();
var timer = setInterval(function() {
$scope.$apply(updateDashboardService.update_dashboard($scope, $http));
}, 1000 * 60);
What I am getting:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- updateDashboardService
Edit 2:
module.service('updateDashboardService', function($rootScope, $http){
this.update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$rootScope.list = data.results;
});
};
});
As #Gopesh says create a factory method, or, you can do something like this in SubmissionTreeController:
$scope.$on("event:updateDashboard", function(){ update_dashboard() });
And in your other controller:
$http.post(url, $scope.selected_items).success(function(data) {
$scope.$emit("event:updateDashboard");
});

Categories