1

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?

5
  • Are you trying to retrieve the value outside of the function? Commented Nov 6, 2014 at 9:46
  • 3
    Be really careful when you use 'this' inside a function. The scope may not be the main one since the javasdcript create a scope for each function. Try to do something like var that = this; outside of the function and use 'that' inside Commented Nov 6, 2014 at 9:46
  • @RahilWazir data will be coming from an external API as shown in code Commented Nov 6, 2014 at 9:48
  • @sam You are right, Main issue was that Commented Nov 6, 2014 at 9:48
  • Good, I will post an answer then if you can validate it ;) Commented Nov 6, 2014 at 9:49

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.