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

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

Related

how can i call function js in another file js ANGULARJS

js1.js
app.controller('test1Controller',
function($scope,$http,$ngBootbox,$location,CRUDService,NotificationService,constants,ngWizard) {
$scope.fun1 = function(){
$http.get(context+"/back/demande/rest/test1").success(function(data, status) {
$scope.dto = data;
});
};
});
js2.js
app.controller('test2Controller',
function($scope,$http,$ngBootbox,$location,CRUDService,NotificationService,constants,ngWizard) {
$scope.fun2 = function(){
$http.get(context+"/back/demande/rest/test2").success(function(data, status) {
$scope.dto = data;
});
};
});
How can I call fun1 => js1.js in js2.js?
First, you need to move your function to angular.js service instance.
Then you need to inject this service to your controllers, like NotificationService.
Then you can call in different controllers.
app.service('myHttpService', ['$http', function($http) {
this.getData = function(context, endpoint) {
return $http.get(context+"/back/demande/rest/" + endpoint);
};
}]
// do not forget to use injector if you don't have ngAnnotate
app.controller('test2Controller', function($scope, $http, $ngBootbox, $location, CRUDService, NotificationService, constants, ngWizard, myHttpService) {
$scope.dto = null;
$scope.fun2 = function(){
myHttpService.getData(context, 'test1')
.then(function(data, status) {
$scope.dto = data;
});
};
});

angular service doesn't fire

I did pretty simple plunker to show my problem. The problem is I have variable and I want to populate this variable with initial app loading, I did angular services for this purpose, but for some reason angular services doesn't fire inside controller. Where is my mistake?
app.controller('MainCtrl', function($scope, optService) {
$scope.priority = [];
var exeService = function() {
console.log('function fired')
// this is firing
optService.myOptions(function (result) {
console.log('service fired')
// this is not firing
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});
}
exeService()
console.log($scope.priority)
// shows an empty array
});
services
(function () {
angular.module("app").factory("optService", ["$http", "$rootScope", "$q", "$log",
function ($http, $rootScope, $q, $log) {
var clearApi = "test.json";
function myOptions () {
return $http.get(clearApi)
.then(function (response) {
console.log(response.data)
// shows an array
return response.data;
});
}
return {
myOptions: myOptions
}
}])
}());
You should do the service declaration like that:
app.controller('MainCtrl', ['$scope', 'optService', function($scope, optService) {
and in the controller
optService.myOptions().then(function (result) {
console.log('service fired')
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});

Create a $http.get properly

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

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

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