AngularJS Factory Usage - json

.factory('MY', function($http){
return {
mustafa: function(){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var yarro = $http.get(url).success(function(response){
return response.data);
});
return yarro;
}
}
})
.controller('nbgCtrl', function() {
$scope.mangas = MY.mustafa();
})
I wanna use json data above like. But it isn't working. Could you guys help me?

You can return the promise, and then resolve it in the controller:
.factory('MY', function($http){
return {
mustafa: function() {
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
return $http.get(url);
}
};
})
Finally, you have to inject the service to the controller.
.controller('nbgCtrl', function($scope, MY) {
MY.mustafa().success(function(response) {
$scope.mangas = response.data;
);
});

Related

Routing is not working in AngularJS

The routing is not working for the index.html. It is even giving a compiler error. Index.html is my startup page. Through Header details link the Add Header.html page should open. I have added the whole code in plunkr ["https://plnkr.co/edit/w9eWiHKvSDrf0viERgoX?p=preview"]
app.js
var MyApp = angular.module('MyApp', ['ngRoute']);
// configure our routes
MyApp.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
// route for the about page
.when('/ProjectIDCreation', {
templateUrl: '/ProjectIDCreation.html',
controller: 'headerCtrl'
})
});
HeaderCtrl.js
var app = angular.module('MyApp');
var baseAddress = 'http://localhost:49754/api/TimeSheet/';
var url = "";
//var app = angular.module('MyApp');
//app.controller('mainController', function ($scope) {
// console.log('mainController');
//});
app.factory('userFactory', function ($http) {
return {
getHeadersList: function () {
url = baseAddress + "FetchHeaderDetails";
return $http.get(url);
},
addHeader: function (user) {
url = baseAddress + "InsertHeaderDetails";
return $http.post(url, user);
},
updateHeader: function (user) {
url = baseAddress + "UpdateHeaderDetails";
return $http.put(url, user);
}
};
});
//var app = angular.module('MyApp');
app.controller('headerCtrl', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = null;
$scope.editMode = false;
//Fetch all Headers
$scope.getAll = function () {
userFactory.getHeadersList().success(function (data) {
$scope.users = data;
}).error(function (data) {
$scope.error = "An Error has occured while Loading users! " + data.ExceptionMessage;
});
};
//Add Header
$scope.add = function () {
var currentUser = this.user;
userFactory.addHeader(currentUser).success(function (data) {
$scope.addMode = false;
currentUser.HeaderID = data;
$scope.users.push(currentUser);
$scope.user = null;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Adding user! " + data.ExceptionMessage;
});
};
//Edit Header
$scope.edit = function () {
$scope.user = this.user;
$scope.editMode = true;
$('#userModel').modal('show');
};
//Update Header
$scope.update = function () {
var currentUser = this.user;
userFactory.updateHeader(currentUser).success(function (data) {
currentUser.editMode = false;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionMessage;
});
};
//Model popup events
$scope.showadd = function () {
$scope.user = null;
$scope.editMode = false;
$('#userModel').modal('show');
};
$scope.showedit = function () {
$('#userModel').modal('show');
};
$scope.cancel = function () {
$scope.user = null;
$('#userModel').modal('hide');
}
// initialize your users data
$scope.getAll();
});
Make sure the file path which you have used in script tags are correct. Which in the plnkr were not correct. Also i found you had two modules defined avoid doing that. Also you are importing angular, jquery, bootstrap more than once dont do that.
Below is the corrected code
Edited plnkr
var app = angular.module('MyApp', ['ngRoute']);
// configure our routes
app.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
// route for the about page
.when('/ProjectIDCreation', {
templateUrl: 'ProjectIDCreation.html',
controller: 'headerCtrl'
})
});
var baseAddress = 'http://localhost:49754/api/TimeSheet/';
var url = "";
app.factory('userFactory', function ($http) {
return {
getHeadersList: function () {
url = baseAddress + "FetchHeaderDetails";
return $http.get(url);
},
addHeader: function (user) {
url = baseAddress + "InsertHeaderDetails";
return $http.post(url, user);
},
updateHeader: function (user) {
url = baseAddress + "UpdateHeaderDetails";
return $http.put(url, user);
}
};
});
//var app = angular.module('MyApp');
app.controller('headerCtrl', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = null;
$scope.editMode = false;
//Fetch all Headers
$scope.getAll = function () {
userFactory.getHeadersList().success(function (data) {
$scope.users = data;
}).error(function (data) {
$scope.error = "An Error has occured while Loading users! " + data.ExceptionMessage;
});
};
//Add Header
$scope.add = function () {
var currentUser = this.user;
userFactory.addHeader(currentUser).success(function (data) {
$scope.addMode = false;
currentUser.HeaderID = data;
$scope.users.push(currentUser);
$scope.user = null;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Adding user! " + data.ExceptionMessage;
});
};
//Edit Header
$scope.edit = function () {
$scope.user = this.user;
$scope.editMode = true;
$('#userModel').modal('show');
};
//Update Header
$scope.update = function () {
var currentUser = this.user;
userFactory.updateHeader(currentUser).success(function (data) {
currentUser.editMode = false;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionMessage;
});
};
//Model popup events
$scope.showadd = function () {
$scope.user = null;
$scope.editMode = false;
$('#userModel').modal('show');
};
$scope.showedit = function () {
$('#userModel').modal('show');
};
$scope.cancel = function () {
$scope.user = null;
$('#userModel').modal('hide');
}
// initialize your users data
$scope.getAll();
});
<li></i>AddHeader</li>
<li></i>ProjectIDCreation</li>
(in .html don't forget / )
.config(
[ '$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/ProjectIDCreation', {
templateUrl: '/ProjectIDCreation.html',
controller: 'headerCtrl'
})
.otherwise('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
}
]);

How to call jsonp api using $http in angularjs

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
$http.jsonp(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
//this is my controller where i calling getUsers();
app.controller('myCtrl', function($scope, users) {
$scope.data = users.getUsers();
})
while calling it gives me error
Uncaught ReferenceError: callback is not defined(anonymous function)
Plz give me proper solution so that i can see me api data in <div>. Thanks in advance
$http already returns a promise. There is no need to form a promise of a promise. Try this:
app.factory('Users', ["$http", function($http){
return {
getUsers: function(url) {
return $http({
url: url,
method: 'JSONP'
});
}
};
}]);
Controller:
app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
$scope.data = [];
Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
console.log(response.data);
$scope.data = response.data;
}).catch(function(response){
console.log(response.statusText);
});
}]);
Here the scenario is a bit different as you have to declare a $window.callback function.
Code
var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {
var getUsers = function () {
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
return $http.jsonp(url);
};
return {
GetUsers: getUsers
}
}]);
app.controller("demoController",
["$scope", "$window", "UserService",
function ($scope, $window, UserService){
UserService.GetUsers();
$window.callback = function (response) {
$scope.countries = response.Results;
}
}]);
Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

Unable to show data in ng-repeat using factory

I have created a factory and making $HTTP request.I have used ng-repeat to show data.Getting data from factory and adding it to $scope variable in controller is unable to show data.The Code is as mentioned below.
I used console.log to get the json returned and it is as mentioned below
JSON:
[{"searchName":"this is test Job","id":"2"},{"searchName":"Job new","id":"1"}]
Angular JS Code:
<script type="text/javascript">
var formApp = angular.module("saveSearch",[]);
formApp.controller("saveSearchController",function($scope,saveServiceSearch)
{
saveServiceSearch.getLatestSaveSearch().then(function(data){
$scope.saveSearches = data;
});
});
formApp.factory('saveServiceSearch', function($http) {
return {
getLatestSaveSearch: function() {
var url = "/job_search_crud.html?act=gtSearchSv";
return promise = $http.get(url,{cache: false});
promise.success(function(data,status, headers, config){
return $data;
});
promise.error(function(data,status, headers, config){
alert("::Request Failed::");
});
}
};
});
</script>
HTML:
<html>
<body ng-app="formApp">
<div ng-controller="saveSearchController">
<table>
<tr ng-repeat="saveSearch in saveSearches" >
<td>{{saveSearch.searchName}}</td>
</tr>
</table>
</div>
</body>
</html>
Try this using $q
myModule.factory('saveServiceSearch', function($q, $timeout, $http) {
var getLatestSaveSearch = function() {
var deferred = $q.defer();
var url = "/job_search_crud.html?act=gtSearchSv";
var data = $http.get(url,{cache: false});
$timeout(function() {
deferred.resolve(data);
}, 2000);
return deferred.promise;
};
return {
getLatestSaveSearch: getLatestSaveSearch
};
});
Edit:
<script type="text/javascript">
var formApp = angular.module("saveSearch",[]);
formApp.controller("saveSearchController",function($scope,saveServiceSearch)
{
saveServiceSearch.getLatestSaveSearch().then(function(data){
$scope.saveSearches = data;
});
});
formApp.factory('saveServiceSearch', function($http) {
return {
getLatestSaveSearch: function() {
var url = "/job_search_crud.html?act=gtSearchSv";
return $http.get(url,{cache: false});
}
}});
</script>

AngularJS : From a factory, how can I call another function

Do I have to move my getTemplates function out of the return or what ?
Example : I dont know what to replace "XXXXXXX" with (I have tried "this/self/templateFactory" etc... ) :
.factory('templateFactory', [
'$http',
function($http) {
var templates = [];
return {
getTemplates : function () {
$http
.get('../api/index.php/path/templates.json')
.success ( function (data) {
templates = data;
});
return templates;
},
delete : function (id) {
$http.delete('../api/index.php/path/templates/' + id + '.json')
.success(function() {
templates = XXXXXXX.getTemplates();
});
}
};
}
])
By doing templates = this.getTemplates(); you are referring to an object property that is not yet instantiated.
Instead you can gradually populate the object:
.factory('templateFactory', ['$http', function($http) {
var templates = [];
var obj = {};
obj.getTemplates = function(){
$http.get('../api/index.php/path/templates.json')
.success ( function (data) {
templates = data;
});
return templates;
}
obj.delete = function (id) {
$http.delete('../api/index.php/path/templates/' + id + '.json')
.success(function() {
templates = obj.getTemplates();
});
}
return obj;
}]);
How about this?
.factory('templateFactory', [
'$http',
function($http) {
var templates = [];
var some_object = {
getTemplates: function() {
$http
.get('../api/index.php/path/templates.json')
.success(function(data) {
templates = data;
});
return templates;
},
delete: function(id) {
$http.delete('../api/index.php/path/templates/' + id + '.json')
.success(function() {
templates = some_object.getTemplates();
});
}
};
return some_object
}
])