user799329 user799329 - 2 months ago 7
AngularJS Question

Not able access javascript local function using angular promise

(function () {
'use strict';

angular
.module('residentialApp')
.factory('LockerBank', ['$q', 'lockerbankService', 'notificationService', 'rfc4122', 'LanguageResourceService', 'StringFormat'
, function ($q, lockerbankService, notificationService, rfc4122, LanguageResourceService, StringFormat) {

var lockerBank = function (lockerBankId, lockerName) {

if (lockerName === undefined) {
lockerName = "";
}

self=this;

if (lockerBankId === undefined) {
lockerBankId = "";
}
this.name = lockerName;
this.id = lockerBankId;

this.description = "";
this.isActive = "";
this.relayEndPointName = "";
this.lockerBankCode = "";
this.createdUtcDate = "";
this.lastHeartBeatUtcDate = "";
this.propertyId = "";
this.mailRoomId = "";
this.address = "";
this.apiToken = "";
this.status = "";

this.lastHeatBeatDateDisplay = "";
this.lastUpdateInSecond = "";
this.createdOnDateDisplay = "";
this.organisationId = "";

return this;
};

lockerBank.prototype = {
initialize: function () {

},

loadFromServer: function (propertyId) {

var defer = $q.defer();
if (this.id === undefined || this.id == null) {
defer.resolve(null);
}
else {
lockerbankService
.loadLockerBank(this.id)
.then(function success(data) {

// The problem is here
self.populateData(data);
var newObject = angular.copy(this);
defer.resolve(newObject);
}, function failure(response) {
defer.reject(response);
});
}
return defer.promise;

},


populateData: function (apiData) {
if (apiData === undefined || apiData == null) {
return;
}

if (this.id === undefined || this.id == null) {
this.id = apiData.Id;
}

}
};

return lockerBank;
}]);

})();


In the above code, i am not able to access the populateData method from then function.

In the scope of the function then i get the object of self=this to be some other object i created already in the application.

I believe there is an issue with scope. IF this was not angular promise then i would use the code as follow

lockerbankService.loadLockerBank(this.id)
.then(function success(data) {
self.populateData(data);
var newObject = angular.copy(this);
defer.resolve(newObject);
}.bind(this))


Can any one help me with this scope issue?

Answer

I can't where you declare self in loadFromServer function. Try this:

loadFromServer: function (propertyId) {
    var self = this;
    var defer = $q.defer();
    ....
Comments