None
None

Reputation: 5670

Unable to set value for Javascript object AngularJS

MY code is like this

  $scope.shipment = new function () {
      this.type = "";
      this.carrier = "";
      this.sInstruction = "";
      this.getInfo = function () {
          if (this.type == 'collect-parcel') {
              $http.post('../services/getratesws.aspx', { 'Content-type': 'application/json' }).
                  success(function(data) {
                      this.sInstruction = data;

                  });
          } 
      };
  }

As you can see I am trying to set value for "sInstruction" inside my function. but the value is not taken and "sInstruction" remains empty.Can any one point out what I am doing wrong?

Upvotes: 1

Views: 47

Answers (2)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

You have set this.sInstruction in your function $scope.shipment, so you can use sInstruction within the scope of function shipment. Now you are trying to do

 $http.post('../services/getratesws.aspx', { 'Content-type': 'application/json' }).
                      success(function(data) {
                          this.sInstruction = data;

                      });

which will obviously not work, as the this in the success function only has a scope limited to the success function.

A solution to this problem would be to save the this from shipment function into a variable and then use it in the success function.

You can do it this way, set var temp=this in the function where you are defining the properties. i.e in your case this should be set in the function shipment but should be out of any other nested function. now you can use temp.sInstruction = data;

Upvotes: 2

sam
sam

Reputation: 3511

When you use 'this' inside a function you can't be sure it will be the same as the main one because in javascript each function has it's own scope.

Try to do the following :

Set this in the code before the function :

var that = this;

And use 'that' inside

Upvotes: 3

Related Questions