i have this code, when i run it i get an error of "ReferenceError: data is not defined" i have defined data in several ways but nothing seem to be correct. the thing is that when i think about it data is declared in api (no?).. would appreciate some help..
app.service('StatisticsService',
['apiClient', '$q', '$rootScope', '$timeout',
function (apiClient, $q, $rootScope, $timeout) {
var self = this;
self.getStatisticsFromServer = function (data) {
var deferred = $q.defer(); //1
apiClient.getStatsTopMeeters(data)
.then(function (response) { //2
console.log('externalApiConnect', response);
if (response.data.length === 0 || response.result !== "success") {
// TODO: show error
deferred.reject(response);
}
var stats = response.data;
stats = self.getUserProfiles(stats);
deferred.resolve(stats);//3
}
, function (error) {
deferred.reject(error);
console.error(error);
});
return deferred.promise; //4
};
self.getUserProfiles = function (stats) {
var deferred = $q.defer();
var emails = [];
for (var i = 0; i < stats.length; i++) {
emails.push(stats[i].email);
}
console.log(emails);
var data2 = {
token: data.token,
profile_emails: emails
};
apiClient.getUserProfiles(data2).then(function (response2) {
console.log('getUserProfiles', (response2));
if (response2.data.length === 0 || response2.result !== "success") {
// TODO: show error
deferred.reject(response2);
}
var stats = response2.data;
deferred.resolve(stats);//3
}
);
};
}]);
this is some of the apiClient page
app.service('apiClient', ['$http', '$q','$rootScope', function ($http, $q, $rootScope) {
var canceler = $q.defer();
var request = function (apiMethod, apiResponse) {
switch (apiMethod) {
case 'set_meeting_note':
case 'get_meeting_details':
case 'get_account_details':
case 'get_availability':
case 'get_best_time':
case 'get_participants_statuses':
case 'check_user_verified_send_email':
case 'get_participants_statuses':
case 'get_user_profiles':
case 'set_calendar_settings':
case 'sync_external_apis':
$rootScope.showLoader = false;
break;
default:
$rootScope.showLoader = true;
break;
}
var config = {
method: 'POST',
url: apiPath + apiMethod,
data: apiResponse,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
withCredentials: true,
timeout: canceler.promise
};
$http(config).success(function (data) {
$rootScope.showLoader = false;
if (data.message === undefined) {
deferred.resolve(data);
} else {
deferred.reject(data);
}
}).error(function (data, status, headers, config) {
$rootScope.showLoader = false;
deferred.reject(data);
});
return deferred.promise;
};
return {
getStatsTopMeeters: function (data) {
return request('get_stats_top_meeters',data );
},
getUserProfiles: function(data){
return request('get_user_profiles',data);
},
}
Related
Upgrade to angularjs version 1.7 and this code does not compile
app.factory('LoginService', function ($http) {
return {
login: function (param, callback) {
$http.post(url, param)
.success(callback)
.error(function (data, status, headers, config) {
});
}
};
});
On the controller I make the call to the service LoginService
function LoginController($http, $location, LoginService, blockUI) {
var vm = this;
LoginService.usuario(
{login: vm.username, clave: vm.password},
function (data, status, headers, config) {
vm.resultado = data;
if (vm.resultado == "True") {
window.location = "/Home/Index";
} else {
vm.error = 'Usuario o password incorrecto';
}
});
};
I want to know how the function is called from the controller because it implemented the http.post service using .then
app.factory('LoginService', function ($http) {
return {
login: function (data) {
$http.post(url, data)
.then(function (resultado) {
debugger;
if (resultado.data === "True") {
return resultado.data;}
else {
console.log("NO");}
});
}};
});
I suggest you get familiar with a AngularJS $q service and its Promise API.
You LoginService.login(...) method should return the Promise from $http.post(...):
app.factory('LoginService', function ($http) {
return {
login: function (data) {
return $http.post(url, data)
.then(function(response) {
return response.data;
});
});
Then, your Controller can access the returned data via the resolved Promise:
function LoginController(LoginService) {
var vm = this;
LoginService.login({login: vm.username, clave: vm.password})
.then(function (result) {
// handle result here...
});
the solution would be this:
function LoginController($scope,$window,$q,LoginService) {
$scope.fnBusqueda = function () {
var promesas = [
obtenerLogin()
];
$q.all(promesas).then(function (promesasRes) {
var oArrayResponse = promesasRes;
if ((oArrayResponse.length > 0)) {
$scope.respuesta = oArrayResponse[0];
if ($scope.respuesta == "True") {
window.location = "/Home/Index";
} else {
$cope.error = 'Usuario o password incorrecto';
}
}
});
};
function obtenerLogin() {
var defered = $q.defer();
var promise = defered.promise;
LoginService.login(url_valida_login, '{login:X,clave:X}').then(function (response) {
defered.resolve(response);
}).catch(function (data) {
defered.resolve([]);
})
return promise;
}
}
I have a controller that passes execution to a factory -- controller.getCustomerById -> factory.getCustomerByID. In this case, the factory function is posting and retrieving data via MVC/angular.$http.post. That all works fine but the subsequent actions in my controller function are executing before the .post is finished.
I've tried making either or both async/await but I think I'm not understanding how to do that. I've tried quite a few of the examples here and elsewhere with no luck.
I have a button that calls setOrderFromGrid which calls getCustomerById. I would assume that making controller.getCustomerById an async function would be the best way but I can't get it to work.
angular.module('aps').factory('TechSheetFactory',
function($http) {
return {
//The ajax that is called by our controller
ITS: function(onSuccess, onFailure) {
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http({
method: "post",
url: "/DesktopModules/MVC/TechSheetMaint/TechSheet/InitializeNew",
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
}
}).then(onSuccess).catch(onFailure);
},
saveTechSheetAng: function(onSuccess, onFailure, techSheetInfo) {
alert(JSON.stringify(techSheetInfo));
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/SaveTechSheetAng",
JSON.stringify(techSheetInfo),
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
} ,
getCustomerById: function(onSuccess, onFailure, customerSearchString) {
alert('factory getcustomerbyid: ' + customerSearchString);
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/GetCustomerById",
{custId:customerSearchString},
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
}
};
});
angular.module('aps').controller('TechSheetCtl', ['TechSheetFactory','$scope', '$rootScope', '$http', '$interval', '$modal', '$log','uiGridConstants',
function (TechSheetFactory,$scope, $rootScope, $http, $interval, $modal, $log) {
/* -----------------SaveTechSheet ------------*/
$scope.saveTechSheet = function() {
if (!$scope.dvTechSheet.$valid) {
$scope.Message = "Form not complete.";
$scope.Status = false;
$scope.showErrors=true;
return;
}
alert($scope.TechSheetInfo.Customer.CustomerID);
if (JSON.stringify($scope.TechSheetInfo.Customer) !== JSON.stringify($scope.TechSheetInfoStatic.Customer) &&
$scope.TechSheetInfo.Customer.CustomerID !== 0) {
if (confirm("You've made changes to this Customer. Save them?") !== true) {
return;
}
}
if (JSON.stringify($scope.TechSheetInfo.WorkOrder) !== JSON.stringify($scope.TechSheetInfoStatic.WorkOrder) &&
$scope.TechSheetInfo.WorkOrder.WorkOrderID !== 0) {
if (confirm("You've made changes to this Work Order. Save them?") !== true) {
return;
}
}
successFunction = function(response) {
var data = response.data.Data;
alert(data);
var techSheet = data.techSheet;
alert(data.status);
if (data.status) {
alert("looks good");
$scope.Message = "";
$scope.showErrors = false;
$scope.TechSheetInfo = techSheet;
alert($scope.TechSheetInfo);
$scope.TechSheetInfoStatic = angular.copy(techSheet);
$rootScope.customerInfo = techSheet.Customer;
createpdf($scope);
} else {
if (response.message !== null) {
$scope.Status = datae.status;
$scope.showErrors = true;
$scope.Message = data.message;
}
}
};
failureFunction = function(data) {
console.log('Error' + data);
};
TechSheetFactory.saveTechSheetAng(successFunction, failureFunction,$scope.TechSheetInfo);
};
/* ----------End SaveTechSheet ---------*/
//------------Initialize a new tech sheet. This is the default action for the page load/refresh/discard changes/clear form
$scope.initializeTechSheet = function() {
$scope.TechSheetInfo = [];
$scope.TechSheetInfoStatic = [];
$scope.customerIDDisabled = false;
$scope.orderIDDisabled = false;
$rootScope.customerInfo = [];
$scope.WindowsPassword = "";
$scope.EmailPassword = "";
const successFunction = function(response) {
$scope.TechSheetInfo = response.data;
$rootScope.customerInfo = response.data.Customer;
$scope.TechSheetInfoStatic = angular.copy(response.data);
};
const failureFunction = function(response) {
//console.log('Error' + response.status);
};
TechSheetFactory.ITS(successFunction, failureFunction);
};
//end initializeTechSheet
$scope.getCustomerById = function(custId) {
const successFunction = function(response) {
alert("success");
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
};
$scope.setOrderFromGrid = function(woInfo) {
$scope.getCustomerById(woInfo.CustomerID);
$scope.TechSheetInfo.WorkOrder = woInfo; //this line and the next are occurring before getCustomerById has completed
$scope.TechSheetInfoStatic.Customer = angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
};
$scope.resetForm = function() {
if (!$scope.dvTechSheet.$pristine) {
if (!confirm("Discard Changes?")) {
return;
}
}
$scope.initializeTechSheet();
$scope.dvTechSheet.$setPristine();
};
}]);
You lose the advantage of the Promises so you can opt-in a Promise this way. (I do not recommend it)
From the top of head something like this:
// inject $q
$scope.getCustomerById = function(custId) {
const deferred = $q.defer()
const successFunction = function(response) {
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
deferred.resolve(); // can pass value if you like
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
deferred.reject();
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
return deferred.promise;
};
/////////////
$scope.setOrderFromGrid = function(woInfo) {
const prom = $scope.getCustomerById(woInfo.CustomerID);
prom.then(()=>{
$scope.TechSheetInfo.WorkOrder = woInfo;
$scope.TechSheetInfoStatic.Customer =
angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
})
};
I'm having some troubles with the local storage and my Ionic app. The thing is quite straight forward - I would like to store to device all the data from from sql database and then display it when the device is without network.
So the code where I get my data from looks like this:
controllers.js:
$http.get('http://someurl.php?type=json')
.success(function(data) {
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
So can anyone help me out with this one?
Thank you!
I can suggest to you to use some plugin for DB but with localstorage you have to pass (and install) this:
angular-local-storage
and then use it in your JS like:
$http.get('http://someurl.php?type=json')
.success(function(data) {
//test if is online or offline and the do something
if($rootScope.isOnLine)
localStorageService.set("nameofkey", { data:data }); //here you store in your localstorage ... remeber to inject it as dependency
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
then if you want to know if your ionic app is online or offline you can use this plugin: http://ngcordova.com/docs/plugins/network/
"use strict";
// Ionic Starter App
angular.module("myapp", ["ionic",
"ionic.service.core",
"ngCordova",
"ionic.service.push",
"ngResource",
"LocalStorageModule",
"ionic-native-transitions",
"angularMoment"])
.run(["$ionicPlatform", "authService", "$rootScope", "$timeout", "$cordovaSpinnerDialog", "$window", "$cordovaNetwork", "$state", "ScanService", "$cordovaToast", "localStorageService", "DB",
function ($ionicPlatform, authService, $rootScope, $timeout, $cordovaSpinnerDialog, $window, $cordovaNetwork, $state, ScanService, $cordovaToast, localStorageService, DB) {
$ionicPlatform.ready(function () {
$rootScope.isOnLine = true;
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (ionic.Platform.isIPad() &&
window.cordova &&
window.cordova.plugins &&
window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
// CONNECTION STATE /////////////////////////////////////////////
if ($cordovaNetwork) {
//listen for OnLine event
$rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
var onlineState = networkState;
$rootScope.isOnLine = true;
});
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
var offlineState = networkState;
$rootScope.isOnLine = false;
});
}
//////////////////////////////////////////////////////////////////
});
}]);
This is an exmaple for a Service using it for call http or from local if there is no connection:
"use strict";
angular
.module('gestione')
.factory("ScanService", ["$q", "$resource", "enviroment", "$rootScope", "localStorageService", "DB",
function ($q, $resource, enviroment, $rootScope, localStorageService, DB) {
var self = this;
// Private Fileds
var _serviceBase = "api/Scan/";
var _serviceBaseBarScan = "api/BarScan/";
var _serviceBaseCount = "api/Scan/Count";
var _serviceBaseLast = "api/Scan/Last";
var _serviceBaseAll = "api/Scan/All";
// Private Method
var _resource = $resource(enviroment.apiUrl + _serviceBase, { skip: '#skip', take: '#take' }, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
var _resourceLast = $resource(enviroment.apiUrl + _serviceBaseLast, {}, {
query: { method: "GET", isArray: false }
});
var _resourceAll = $resource(enviroment.apiUrl + _serviceBaseAll, {}, {
create: { method: "POST", isArray: true }
});
var _resourceCount = $resource(enviroment.apiUrl + _serviceBaseCount, {}, {
query: { method: "GET", isArray: false }
});
var _resourceBar = $resource(enviroment.apiUrl + _serviceBaseBarScan, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
return {
Get: function (skip, take) {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resource.query({ skip, take }).$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC ;").then(function (result) {
var scan = DB.fetchAll(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetLast: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceLast.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC LIMIT 1 ;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetNotSync: function () {
return DB.Query("SELECT * FROM Scan WHERE sync = ? ", ['false']).then(function (result) {
return DB.fetchAll(result);
});
},
CheckInOrOut: function (item) {
return DB.Query("SELECT * FROM Scan WHERE idTicket = ? ORDER BY ROWID DESC LIMIT 1;", [item.IdTicket]).then(function (result) {
return DB.fetch(result);
});
},
Count: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceCount.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT COUNT(*) FROM Scan;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
Save: function (scan) {
var deferred = $q.defer();
//We're OnLine
if ($rootScope.isOnLine) {
_resource.create(scan).$promise.then(function () {
scan.sync = true;
}).catch(function () {
scan.sync = false;
}).finally(function () {
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
});
} else { // OffLine
scan.sync = false;
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
}
return deferred.promise;
},
Sync: function () {
var self = this;
var deferred = $q.defer();
var allPromise = [];
//get all stored scans
self.GetNotSync().then(function (scanList) {
// send them to the server
if (scanList && scanList.length > 0)
_resourceAll.create(scanList).$promise.then(function (resp) {
//cicle on each record returned from server
resp.forEach(function (item) {
if (item) {
//prepare query
var update_query = "UPDATE Scan SET sync= 'true' WHERE idTicket= " + item.idTicket;
//set sync to true on records
allPromise.push(DB.Update(update_query));
}
});
}).catch(function (err) {
allPromise.push(deferred.reject(err));
});
}).catch(function (error) { allPromise.push(deferred.reject(error)); });
return $q.all(allPromise);
},
GetBarScan: function () {
return _resourceBar.query();
},
SaveBarScan: function (barscan) {
var deferred = $q.defer();
_resourceBar.create(barscan).$promise.then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
return deferred.promise;
}
};
}
]);
I am getting this error.. not sure what's the problem..
TypeError: StatisticsService.getStatisticsFromServer is not a function
i cant seem to see the problem, not sure what i'm doing wrong
this is the controller
app.controller('StatisticsCtrl',
['$scope',
'$auth',
'StatisticsService',
function ($scope, $auth, StatisticsService) {
var token = $auth.getToken();
console.log('StatisticsCtrl INIT');
function run() {
var data = {
token: token,
timestamp_from: moment(new Date()).unix()-30 * 24 * 3600,
timestamp_till: moment(new Date()).unix(),
order: 'duration_minutes',
limit: 20
};
//
StatisticsService.getStatisticsFromServer(data).then(function (response) {
console.log('syncStatistics', (response));
$scope.statistics = response;
// $scope.statistics = StatisticsService.buildStatsUsers(response.data); // jason comes from here
}, function (error) {
console.error(error);
});
}
run();
}]);
this is the server
app.service('StatisticsService',
['apiClient', '$q', '$rootScope', '$timeout',
function (apiClient, $q, $rootScope, $timeout) {
var self = this;
self.getUserProfiles = function (stats) {
var emails = [];
for (var i = 0; i < stats.length; i++) {
emails.push(stats[i].email);
}
console.log(emails);
var data2 = {
token: data.token,
profile_emails: emails
};
apiClient.getUserProfiles(data2).then(function (response2) {
console.log('getUserProfiles', (response2));
if (response2.data.length === 0 || response2.result !== "success") {
// TODO: show error
deferred.reject(response2);
}
var stats2= response2.data;
deferred.resolve(stats);//3
}
);
self.getStatisticsFromServer = function (data) {
var deferred = $q.defer(); //1
apiClient.getStatsTopMeeters(data)
.then(function (response) { //2
console.log('externalApiConnect', response);
if (response.data.length === 0 || response.result !== "success") {
// TODO: show error
deferred.reject(response);
}
var stats = response.data;
stats = self.getUserProfiles(stats);
deferred.resolve(stats);//3
}
, function (error) {
deferred.reject(error);
console.error(error);
});
return deferred.promise; //4
};
};
}]);
You're defining self.getStatisticsFromServer inside the function self.getUserProfiles. So, the function indeed doesn't exist in the service until you call getUserProfiles() at least once. And it's replaced at each invocation. I doubt that's what you want.
I am just beginning to learn AngularJS and have a problem understanding promises. I have
factory which makes call to back-end server and returns a promise as follows:
var commonModule = angular.module("CommonModule", [])
.factory('AjaxFactory', function($http, $q, $dialogs, transformRequestAsFormPost) {
return {
post: function(reqUrl, formData) {
var deferred = $q.defer();
$http({
method: "post",
url: reqUrl,
transformRequest: transformRequestAsFormPost,
data: formData
}).success(function(data) {
if (data['error']) {
if (data['message']) {
$dialogs.notify('Error', data['message']);
} else {
}
} else if (data['success']) {
if (data['message']) {
$dialogs.notify('Message', data['message']);
}
} else if (data['validation']) {
}
deferred.resolve(data);
}).error(function(data) {
$dialogs.notify('Error', 'Unknown Error. Please contact administrator');
});
return deferred.promise;
}
};
})
.factory("transformRequestAsFormPost", function() {
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
return(serializeData(data));
}
return(transformRequest);
function serializeData(data) {
if (!angular.isObject(data)) {
return((data === null) ? "" : data.toString());
}
var buffer = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent(name) +
"=" +
encodeURIComponent((value === null) ? "" : value)
);
}
var source = buffer
.join("&")
.replace(/%20/g, "+")
;
return(source);
}
}
);
I have a controller which calls the AjaxFactory service using two functions as follows
marketingCampaignModule.controller('CampaignInfoController', ['$scope', 'AjaxFactory', '$state', 'campaign', function($scope, AjaxFactory, $state, campaign) {
$scope.init = function() {
$scope.name = campaign['name'];
$scope.description = campaign['description'];
console.log($scope.mcmcid);
if ($scope.mcmcid > 0) {
var inputData = {};
inputData['mcmcid'] = $scope.mcmcid;
var ajaxPromise1 = AjaxFactory.post('index.php/mcm/infosave/view', inputData);
ajaxPromise1.then(function(data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
function(data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
}
);
}
};
$scope.init();
$scope.submitForm = function(isValid) {
if (isValid) {
var formData = $scope.prepareFormData();
var ajaxPromise = AjaxFactory.post('index.php/mcm/infosave/save', formData);
ajaxPromise.then(function(data) {
if (data['success']) {
$scope.setValues(data['params']);
} else if ('validation') {
$scope.handleServerValidationError(data['message']);
}
});
}
};
$scope.prepareFormData = function() {
mcmcId = '';
var formData = {};
if ($scope.mcmcid > 0) {
mcmcId = $scope.mcmcid;
}
formData["mcmcid"] = mcmcId;
formData["name"] = $scope.name;
formData["description"] = $scope.description;
return formData;
};
$scope.setValues = function(data) {
$scope.mcmcid = data['mcmcid'];
$state.go('TabsView.Companies');
};
$scope.handleServerValidationError = function(validationMessages) {
alert(validationMessages['name']);
};
}]);
The promise ajaxPromise gets resolved in the function $scope.submitform but not in $scope.init.
Please tell me what am I missing.
add to your service deffere.reject() on error:
app.factory('AjaxFactory', function($http, $q, $dialogs, transformRequestAsFormPost) {
return {
post: function(reqUrl, formData) {
var deferred = $q.defer();
$http({
method: "post",
url: reqUrl,
transformRequest: transformRequestAsFormPost,
data: formData
}).success(function(data) {
if (data['error']) {
if (data['message']) {
$dialogs.notify('Error', data['message']);
} else {
}
} else if (data['success']) {
if (data['message']) {
$dialogs.notify('Message', data['message']);
}
} else if (data['validation']) {
}
deferred.resolve(data);
}).error(function(data) {
deferred.reject(data)
$dialogs.notify('Error', 'Unknown Error. Please contact administrator');
});
return deferred.promise;
}
};
});
and in you controller handle error:
$scope.init = function () {
$scope.name = campaign['name'];
$scope.description = campaign['description'];
console.log($scope.mcmcid);
if ($scope.mcmcid > 0) {
var inputData = {};
inputData['mcmcid'] = $scope.mcmcid;
var ajaxPromise1 = AjaxFactory.post('index.php/mcm/infosave/view', inputData);
ajaxPromise1.then(function (data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
function (data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
//on error
function (data) {
alert("error");
console.log(data);
});
}
};