load jsonp into multiple AngularJS controllers - angularjs

I have a jsonp call to a server which returns an object containing two objects.
At the moment I make the jsonp call with jQuery because I've just started learning AngularJS and I dont know how it's done.
I want to use data.filters in navController and data.results in contentController
What would be the correct way to achieve this with AngularJS ?
(function($, angular) {
$(function() {
$.ajax({
jsonp: "JSONPCallback",
url: 'myUrl',
dataType: 'jsonp',
success: function(data) {
//data = {"filters":{...},"results":{...}}
}
});
});
var app = angular.module('app', []);
var controllers = {};
controllers.navController = function($scope) {
$scope.filters = [{}];
};
controllers.contentController = function($scope) {
$scope.results = [{}];
};
app.controller(controllers);
})(jQuery, angular);

Hi please see here http://plnkr.co/edit/hYkkQ6WctjhYs8w7I8sT?p=preview
var app = angular.module('plunker', []);
app.service('dataService', function($http){
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
var dataReady= false
var filters = [];
var results = [];
function getData() {
if (dataReady)
retrun
else
{
$http.jsonp(url)
.success(function(data){
//in your case
//angular.copy(data.filters, filters)
//angular.copy(data.results , results )
angular.copy(data.posts[0], results);
angular.copy(data.posts[1], filters);
dataReady = true
}).error(function(){
alert('cant load data');
});
}
}
return {
filters : filters,
results : results,
getData : getData
}
})
app.controller('MainCtrl', function($scope,dataService) {
$scope.name = 'World';
$scope.items = dataService.results;
dataService.getData();
});
app.controller('SecondCtrl', function($scope,dataService) {
$scope.filters = dataService.filters;
dataService.getData();
});

Related

Calling only once or caching the data from a $http get in an AngularJS service

I have a simple app in DNN. Below is my code.
What am I trying to do is create a service which call the GET api once. So when the same data from input were called twice the service will call the same api. I'm using network in inspect element to find the calling functions.
<script type="text/javascript">
'use strict';
var myApp<%=ModuleId%> = {};
var isDlgOpen;
try {
myApp<%=ModuleId%> = angular.module('myApp<%=ModuleId%>', ['ngMaterial', 'ngMessages']);
}
catch (e) {
myApp<%=ModuleId%> = angular.module('myApp<%=ModuleId%>', ['ngMaterial', 'ngMessages']);
}
//Service
myApp<%=ModuleId%>.service('myService', ['$http', '$q', function ($q, $http) {
this.data;
var self = this;
this.submit = function () {
if (angular.isDefined(self.data)) {
return $q.when(self.data)
}
return $http.get($scope.apiGetUrl).then(function (response) {
self.data = response;
})
}
}]);
//Controller
myApp<%=ModuleId%>.controller('myCtrlr<%=ModuleId%>', function (myService, $scope, $http, $mdDialog) {
$scope.submit = function (ev) {
$scope.portalAlias = 'http://<%=PortalSettings.PortalAlias.HTTPAlias %>';
$scope.apiGetUrl = $scope.portalAlias + '/desktopmodules/ORSIModule/api/RepairStatus/getRepair?JobNo=' + $scope.jobNo + '&SerialNo=' + $scope.serialNo;
//form is valid
if ($scope.myForm.$valid) {
$scope.isLoading = true;
return $http.get($scope.apiGetUrl).then(
function (response) {
if (response.data) {
$scope.myForm.$setSubmitted();
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('dnnModule<%=ModuleId%>')))
.clickOutsideToClose(true)
.title('title: ' + response.data.status)
.textContent('Thank you.')
.ariaLabel('Status Alert Dialog')
.ok('Close')
.targetEvent(ev)
.hasBackdrop(false)
);
} else {
alert("Not found.");
}
});
}
};
});
// Bootstrap the module
var appDiv = document.getElementById("dnnModule<%=ModuleId%>");
angular.bootstrap(appDiv, ["myApp<%=ModuleId%>"]);
Please somebody help me thanks
You just need to set the cache property to true in the get request:
$http.get(url, { cache: true}).success(...);
Also you can use:
$http({ cache: true, url: url, method: 'GET'}).success(...);
Another approach is to use cachefactory service:
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}

Load first json object by default - Angular

I'm hoping this is an easy question to answer...
I'm trying to create a table that loads my json, then be able to click a row and load more details that pertain to the json object. When you click a row it should load additional details at the top of the page. The row clicking part is working fine. What I'm having trouble with is loading the initial object by default.
Below is an example of what I'm referring to:
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function (item) {
$scope.selected = item;
}
}]);
http://embed.plnkr.co/6LfAsaamCPPbe7JNdww1/
I tried adding this after $scope.select, but got an error:
$scope.selected = item[0];
How do I get the first object in my json to load by default?
thanks in advance
Inside your promise resolve function assign the first item of the array, as a selected value:
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log(data);
});
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log($scope.itemDetails);
console.log($scope.selected);
});
}]);

Angular service passing data to controller

I am trying to create a service that passes data to controller.
I cannot see any errors in the console but yet the data won't show. What exactly am I doing wrong?
Service
app.service('UsersService', function($http, $q) {
var url = '/users';
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
});
Controller
app.controller('contactsCtrl',
function($scope, $routeParams, UsersService) {
// Get all contacts
UsersService.get().then(function(data) {
$scope.contacts = data;
});
});
success is now deprecated.
app.service('UsersService', function($http) {
var url = '/users';
this.get = function() {
return $http.get(url).then(function(response) {
return response.data;
});
}
});
you are referring to UsersService.get(), so you must define the .get() function to call:
app.service('UsersService', function($http, $q) {
var url = '/users';
this.get = function() {
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
}
});

ionic http.get doesn't work in factory

So i can get data from a URL if i do it from with in my controller. But if i take that and move it into a factory it doesn't work. So what am i doing wrong?
angular.module('starter.notifications', [])
.factory('Notifications', function($http) {
var link = "http://localhost:8000/notifications";
var notifications = [];
return {
getAll: function()
{
return $http.get(link).success(function(data, status, headers, config) {
notifications = data;
return notifications;
});
},
This code works if i move it into a controller, but why doesn't it work in a factory?
This is how i did it.
In the top of your app.js
angular.module('app', ['ionic', 'app.controllers', 'app.services','ngCordova'])
Let ionic knows you have an services.js by declaring it.
services.js (an http post request example)
angular.module('app.services', ['ngCordova'])
.factory('dataFactory', function($http, $cordovaGeolocation){
var dataFactory = {};
dataFactory.login = function(username, password){
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
var data = 'userID=' + username + '&password=' + password +'';
var httpAddressDoLogin = "http://YOURURL";
return $http.post(httpAddressDoLogin, data, config);
};
return dataFactory;
})
In your controller:
dataFactory.login(username, password).then(function(resp) {
Hope that helps.
On services.js $http.get resulting promise not object array. To make it work write like this on your services.js
angular.module('starter.services', [])
.factory('Actor', function($http) {
var actors = $http.get('http://ringkes/slim/snippets/actor').then(function(resp) {
if (resp) {
return = resp['data'];// This will produce promise, not array so can't call directly
} else {
console.error('ERR', err);
}
});
return {
all: function() {
return actors;
}
};
});
then call it on controller like this:
controller('DashCtrl', function($scope,Actor,$http) {
Actor.all().then(function(actors){ $scope.actors = Actor.all();
});
});

Angular Js : undefined value in pop up

I get a problem in AngularJS when getting data from JSON using service factory ($resource)
services.factory('GetCustomerByEmailFactory', function ($resource) {
return $resource(url + '/customerService/getCustomerByMail?email=:email', {}, {
getByMail: { method: 'GET', params: {email: '#email'} }
});
});
this service works well
but the controller part doesn't work
app.controller('CustomerCreationCtrl', ['$scope','PostCustomerFactory', '$location','Subscription','AddNotificationFactory','$routeParams','GetCustomerByEmailFactory',
function ($scope, PostCustomerFactory, $location,Subscription,AddNotificationFactory,$routeParams,GetCustomerByEmailFactory) {
$scope.customer ={};
$scope.not ={};
$scope.aftercustomer ={};
$scope.createNewCustomer = function(){
Number($scope.customer.PhoneNumber);
$scope.customer.SubscriptionDate = "1990-02-23T00:00:00";
$scope.customer.ManagerIdCustomer=1;
PostCustomerFactory.create($scope.customer);
var customer = GetCustomerByEmailFactory.getByMail({email:$scope.customer.Email}).$promise;
customer.then(function (responce){
$scope.aftercustomer = responce;
window.alert($scope.aftercustomer.Id);
$scope.not.CustomerId = $scope.aftercustomer.Id;
$scope.not.ManagerId = $routeParams.id;
AddNotificationFactory.create($scope.not);
});
$location.path("/login");
};
}]);
the window.alert show me an undefined value so that it doesn't get the data

Resources