Sam Sam - 9 months ago 66
AngularJS Question

JavaScript Promise and the this keyword

Given the following JS, how do I set the

message
property of the
PlateCheck
object?

var plateCheck = {
plateNumber: '',
message: '',
alertClass: '',
checkPlate: function (plateNumber) {
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;

if (data.VehicleAtl !== null) {
this.message = "Hot!";
this.alertClass = 'alert-danger';
} else {
this.message = "Plate #" + data.PlateNumber + " is clean.";
this.alertClass = 'alert-success';
}
});
}
};


Edit

PlateCheckService.checkPlate(plateNumber)
returns a promise...

Answer Source

This may be just a scoping issue, but to return the same object by calling plateCheck.checkPlate(fooPlateNumber) maybe this will do the trick.

var plateCheck = {
        plateNumber: '',
        message: '',
        alertClass: '',
        checkPlate: function (plateNumber) {
            var me = this;
            PlateCheckService.checkPlate(plateNumber).then(function (response) {
                var data = response.data;
                me.plateNumber = plateNumber;
                if (data.VehicleAtl !== null) {
                    me.message = "Hot!";
                    me.alertClass = 'alert-danger';
                } else {
                    me.message = "Plate #" + data.PlateNumber + " is clean.";
                    me.alertClass = 'alert-success';
                }
            });
        }
    };

But maybe you could just extract the service function, to return a plateCheck object as such.

function checkPlate(plateNumber) {
    var plateCheck = {};
    plateCheck.plateNumber = plateNumber;
    PlateCheckService.checkPlate(plateNumber).then(function (response) {
        var data = response.data;
        if (data.VehicleAtl !== null) {
            plateCheck.message = "Hot!";
            plateCheck.alertClass = 'alert-danger';
        } else {
            plateCheck.message = "Plate #" + data.PlateNumber + " is clean.";
            plateCheck.alertClass = 'alert-success';
        }
    });
    return plateCheck;
}