callback function not called in angularjs - javascript

I have written a callback method in angularjs. But somehow, it is not called. My code is as follows.
Link function:
link: function(scope, element, attrs) {
scope.getContent = function(itemId) {
getTocService.getArtData(itemId, function(data){
var art = data;
alert(art);
});
}
element.append("<collection collection='member.tocItem'></collection>");
$compile(element.contents())(scope)
}
Service:
app.service(
"getTocService",
function( $http, $q ) {
return({
getArtData: getArtData
});
function getToc(bookIdvar) {
var request = $http({
method: "post",
url: "http://10.132.241.41:8082/apdpoc/services/ApdBookService/getTOC",
params: {
action: "post"
},
data: {
getTOCCriteria:{
bookId: bookIdvar
}
}
});
return( request.then(handleSuccess,handleError));
}
function getArtData(itemId, cb) {
var request = $http({
method: "post",
url: "http://10.132.241.41:8082/apdpoc/services/ApdBookService/getArticle",
params: {
action: "post"
},
data: {
getArticleCriteria:{
articleId: itemId,
locale: "en_US"
}
}
});
return(request.then(handleSuccess,handleError), cb);
}
function handleSuccess(response){
return (response.data);
}
function handleError( response ) {
if (
! angular.isObject(response.data) ||
! response.data.message
) {
return($q.reject("An unknown error occurred."));
}
return($q.reject(response.data.message));
}
}
);
As per my little knowledge on angularJs,
the call back method should execute
var art = data;
alert(art);
these lines. but control is not coming over there. Can someone let me know what is the problem here?

You should update
return(request.then(handleSuccess,handleError), cb);
to
return(request.then(cb,handleError));

Related

Angular throwing exception 'module cant be loaded'!

I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -
Error: $injector:modulerr
Module Error
Then I tried searching for the why the module won't load but with no luck.
main.js /*File where app module is declared*/
var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
I tried injecting the dependency for the controller files.
Controllers:
Link Controller
var app = angular.module('app');
app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*First AJAX request which gets all the links and categories for the user*/
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
$scope.getUser = function () {
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
};
$http({
method: 'GET',
url: '/links'
}).then(function successCallback(response) {
this.orderProp = 'age';
/*the response is saved in scope variables*/
$scope.links = response.data[0];
$scope.categories = response.data[1];
$scope.categorytolink = response.data[2];
}, function errorCallback(response) {
console.log('There was a problem! Refresh!');
});
/*AJAX request for getting the recommendations according to the most viewed stars*/
$http({
method: 'GET',
url: '/recommendations/top'
}).then(function successCallback(response) {
$scope.recommendations = response.data;
}, function errorCallback(response) {
});
/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
$http({
method: 'GET',
url: "/proxy",
headers: {
"X-Proxy-To": link.rss_link
}
}).then(function successCallback(response) {
/*AJAX request: add a star to the link*/
$http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {
// Manually increment star for link just clicked
var $data;
$data = data.data;
$scope.link = $data;
console.log('200 OK! Star added');
}, function errorCallback() {
console.log('Error!');
});
/*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/
$myXml = response.data;
$xmlObj = $.parseXML($myXml);
$newsItems = [];
$channelImage = $($xmlObj).find("channel>image");
/*the information of the link is sorted */
$linkData = {
"title": $channelImage.find("title").text(),
"link": $channelImage.find("link").text(),
"imgurl": $channelImage.find("url").text()
};
/*the data is sorted below*/
$.each($($xmlObj).find("item"), function (index, value) {
$newsItems.push({
"title": $(value).find("title").text(),
"description": $(value).find("description").text(),
"link": $(value).find("link").text(),
"date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
"time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
"guid": $(value).find("guid").text()
})
});
$scope.newsItems = $newsItems;
$scope.linkData = $linkData;
}, function errorCallback(response) {
});
};
/*Create a category private to the user*/
$scope.create_category = function (category) {
/*AJAX request: adds a new category*/
$http.post('/categories/new', {'category': category}).then(function successCallback(response) {
/*AJAX request: Updates the categories for the use of new category*/
$http({
method: 'GET',
url: '/categories'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
});
}, function errorCallback(response) {
});
};
}]);
User Controller
var app = angular.module('app');
app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.dzOptions = {
paramName: "file",
dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
createImageThumbnails: false,
autoDiscover: false
};
$scope.dzCallbacks = {
'sending': function (file, xhr, formData) {
formData.append('_token', $('#csrf-token').val());
},
'success': function (file, response) {
$scope.user = response;
$.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
}
};
/*Update user info*/
$scope.updateUser = function () {
/*AJAX request: update user info*/
$http.post('/users/update', {
'name': $scope.user.name,
'username': $scope.user.username,
'email': $scope.user.email
}).then(
function successCallback(data) {
$scope.user = data;
$.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
console.log('200 OK! User updated');
}, function errorCallback() {
console.log('Error!');
});
};
}]);
Article Controller
var app = angular.module('app');
app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*Populates the comments for particular
* */
$scope.populatecomments = function (newsItem) {
$http({
method: 'GET',
url: '/articles/' + newsItem.guid + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
});
};
$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
if ($scope.txtcomment != '') {
$scope.data.push({
"comment": $scope.txtcomment,
"guid": newsItem.guid
});
$http.post('/comments/new', {
"comment": $scope.txtcomment,
"guid": newsItem.guid
}).then(function successCallback() {
var encodedURI = encodeURIComponent(newsItem.guid);
$http({
method: 'GET',
url: '/articles/' + encodedURI + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
$scope.txtcomment = "";
}, function errorCallback(response) {
});
}, function errorCallback() {
console.log('Error comment!');
});
}
};
$scope.savearticle = function (newsItem) {
$http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
/*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
}, function errorCallback(response) {
});
}
/**
* The saved articles by the user will be retrieved when a button clicked
*/
$scope.getSavedArticles = function () {
/*AJAX request: retreive the saved the saved articles for the user*/
$http({
method: 'GET',
url: '/saved-articles'
}).then(function successCallback(response) {
$scope.linkData = null;
$scope.newsItems = response.data;
}, function errorCallback(response) {
});
};
}]);
HELP needed!
Yo do not need to declare module in each controller file. Remove the line in each controller
var app = angular.module('app');
You are injecting controller in you module like dependency.
Change your main.js file to this:
var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
#Sajeetharan is right you do not need module declaration in all controllers.
Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )
There are two ways to do this:
Change the Angular Tags
var app = angular.module('app', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
Now Laravel will use the {{ variableName }} and Angular will use <%
variableName %>.
Change the Laravel Blade Tags
Blade::setContentTags('<%', '%>');// for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
Variables will be: <% $variable %>. Comments will be: <%-- $variable
--%>. Escaped data will look like: <%% $variable %%>.
You can check this Tutorial for more info.

How to return transformed data from a $http.json request in angular?

How can I return the APIData.map and not the default success APIdata using $http.jsonp?
LangDataService Constructor:
languages.LangDataService = function($http, $q) {
this.langDefer = $q.defer();
this.isDataReady = this.langDefer.promise;
};
languages.LangDataService.prototype.getApi = function() {
return this.isDataReady = this.http_.jsonp(URL, {
params: {}
})
.success(function(APIData) {
return APIData.map(function(item){
return item + 1; //just an example.
});
});
};
A Ctrl using LandDataService:
languages.LanguageCtrl = function(langDataService) {
languages.langDataService.isDataReady.then(function(data){
console.log('whooo im a transformed dataset', data);
});
}
Use then instead of success in getApi function.
Try a version of the following:
https://jsfiddle.net/L2ndft4w/
// define the module for our AngularJS application
var app = angular.module('App', []);
app.factory('LangDataService', function($q,$http) {
return {
getApi: function() {
var defer= $q.defer();
$http({
url: 'https://mysafeinfo.com/api/data?list=zodiac&format=json&alias=nm=name',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).
success(function (data) {
defer.resolve(data.map(function(item){
return item.name;
}));
})
return defer.promise;
}
};
});
// invoke controller and retrieve data from $http service
app.controller('DataController', function ($scope, LangDataService) {
LangDataService.getApi().then(function(data){
$scope.data = JSON.stringify(data, null, 2);
});
});
Returns:
[
"Aquarius",
"Aries",
"Cancer",
"Capricorn",
"Gemini",
"Leo",
"Libra",
"Ophiuchus",
"Pisces",
"Sagittarius",
"Scorpio",
"Taurus",
"Virgo"
]
Although, since $http is already a promise, there's probably a shorter way to do this... ($q.when?)

AngularJS $http get doesn't work but $.ajax does

I am new to AngularJS. I cannot seem to get $http to work. I have the following factory:
app.factory('employeeFactory', function ($http) {
var factory = {};
// get data form controller
var employees = [];
var Url = "../../../Employee/GetEmployees";
// this does not work ----------------------------
$http.get(Url, { params: { term: 'Step' }}).
success(function (response, status, headers, config) {
employees = response.data
}).
error(function (response, status, headers, config) {
alert(error);
});
// this works using JQuery ajax ----------------------------
$.ajax({
url: Url,
data: { term: 'Step' },
dataType: "json",
type: "GET",
error: function (request, status, error) {
alert(error);
},
success: function (response) {
$.each(response.data, function (i, obj) {
employees.push({ EmployeeName: obj.EmployeeName, EmployeeNumber: obj.EmployeeNumber });
});
}
});
factory.getEmployees = function () {
return employees
};
return factory;
});
And the following controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
init();
function init() {
$scope.employees = employeeFactory.getEmployees();
}
});
The ajax call in the factory works but the $https doesn't (both are in the factory, I just comment out one or the other while testing). I looked in google chrome dev tools and both calls return data in the same format, but the $http data is not being bound to the html:
<div class="container">
<h4>This is view 1</h4>
Type a name to filter: <input type="text" data-ng-model="employeeSearch" />
<ul>
<li data-ng-repeat="employee in employees | filter:employeeSearch | orderBy:'EmployeeName'">{{ employee.EmployeeName }} - {{ employee.EmployeeNumber }}</li>
</ul>
</div>
Here is the format the factory returns for both calls:
{data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
0: {EmployeeNumber:123456, EmployeeName:Johnson,Bob}
EmployeeName: "Johnson,Bob"
EmployeeNumber: "123456"
I don't understand why, when both calls return the data to the view in the same format, the binding is not occurring with the $http method. Any help is appreciated
The jQuery ajax works because you push to the returned reference.
In the angular ajax success handler you overwrite the variable, but the return value is still the empty reference.
So to get the angular $http function working, you should do the following in your success handler:
angular.forEach(response.data, function(value) {
employees.push(value);
});
use this code:
service:
app.factory('employeeFactory', function ($http) {
var employees = [];
var Url = "../../../Employee/GetEmployees";
var factory = {
getEmp:function(){
return $http.get(Url, { params: { term: 'Step' }})
}
}
return factory;
});
controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
function init() {
employeeFactory.getEmp().then(function(data){
$scope.employees=data;
})
.catch(function(err){
console.log(err);
})
}
init();
});

Using a factory inside another factory AngularJS

I have a module...
angular.module('myModule', []);
And then a factory
angular.module('myModule')
.factory('factory1', [
function() {
//some var's and functions
}
]);
And then another factory
angular.module('myModule')
.factory('factory2', [
function() {
//some var's and functions BUT I want to use some var's from factory1
}
]);
But I want to use some variables from factory1 inside factory2, how can I inject factory1 into factory2?
This is what I would do:
On Factory One
angular.module('sampleApp')
.factory('factory1', function() {
var factory1 = {};
factory1.method1 = function () {
return true;
};
factory1.method2 = function () {
return "hello";
};
return factory1;
}
);
On Factory Two
angular.module('sampleApp')
.factory('factory2', ['factory1',
function(factory1) {
var factory2 = {};
factory2.method3 = function () {
return "bye vs " + factory1.method2();
};
return factory2;
}
]);
This is what i did and worked fine. Call SessionPresenters from Session
angular.module('tryme3App')
.factory('Session', function ($resource, DateUtils, SessionPresenters) {
return $resource('api/sessions/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
var result = SessionPresenters.get({id: data.id})
data.presenters = result;
return data;
}
},
'update': { method:'PUT' }
});
}).factory('SessionPresenters', function ($resource, DateUtils) {
return $resource('api/session.Presenters/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET', isArray: true
},
'update': { method:'PUT' }
});
});

AngularJS $resource & cache factory

I have implemented angular $resource with custom functions and parameters as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
return $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
}]);
And I am consuming this in the controller as follows:-
.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
$scope.candidateList = [];
CandidateService.getAll(function (data) {
$scope.candidateList = data;
});
}]);
This is working absolutely fine. Now I need to cache the data from the api into the CandidateService Factory so it is not loaded eveytime I move between the controllers.
So I thought i would do something as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
var Api = $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
var candidateDataLoaded = false;
var candidateData = [];
return {
getCandidates: function () {
if (!candidateDataLoaded) {
Api.getAll(function (data) {
angular.copy(data, candidateData);
});
}
return candidateData;
}
}
}]);
But I just cant get this to work. I think it has something to do with angular factory being a singleton.
Is my approach correct to implement the caching?
You can use the $cacheFactory object.
See : http://docs.angularjs.org/api/ng.$cacheFactory
You can cache $http request like that :
var $httpDefaultCache = $cacheFactory.get('$http');
If you want to retrieve a specific url in cache do :
var cachedData = $httpDefaultCache.get('http://myserver.com/foo/bar/123');
$You can clear the cache too :
$httpDefaultCache.remove('http://myserver.com/foo/bar/123');
or :
$httpDefaultCache.removeAll();
Complete post here : Power up $http with caching

Categories

Resources