0

I use Jquery in my angular project.I try to access the value of this.selectedUrl but when it jumps into the Jquery ready function it gives UNDEFINED.How to do it?

this.selectedUrl = this.router.url
   console.log("this.selectedUrl",this.selectedUrl)  // gives value i.e /home
   $(document).ready(function () {
     console.log("this.selectedUrl",this.selectedUrl)  // gives undefiend
     if(this.selectedUrl=="/home"){
      console.log("this.selectedUrlIf",this.selectedUrl)
     }

  });

2 Answers 2

4

First is angular does not need jquery to handle any functionalities. Still , in this case you are getting undefined because using of function key word with $(document). Inside $(document).ready(function () this will get a complete new scope and it does not know what is selectedUrl. You can explore arrow function

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

Comments

0

this takes a completely different value inside ready function unless you bind this to the function

For example:

this.selectedUrl = this.router.url
   console.log("this.selectedUrl",this.selectedUrl)  // gives value i.e /home
   $(document).ready(function () {
     console.log("this.selectedUrl",this.selectedUrl)  // this is now available
     if(this.selectedUrl=="/home"){
      console.log("this.selectedUrlIf",this.selectedUrl)
     }

  }.bind(this));

or use the ES6 arrow functions which take this from the parent scope

this.selectedUrl = this.router.url
   console.log("this.selectedUrl",this.selectedUrl)  // gives value i.e /home
   $(document).ready(()=>{
     console.log("this.selectedUrl",this.selectedUrl)  // this is now available
     if(this.selectedUrl=="/home"){
      console.log("this.selectedUrlIf",this.selectedUrl)
     }

  });

a third option is to store this to another variable and refer to that variable instead. For example:

var that = this; // store to variable
this.selectedUrl = this.router.url
   console.log("this.selectedUrl",this.selectedUrl)  // gives value i.e /home
   $(document).ready(function () {
     console.log("this.selectedUrl",that.selectedUrl)  // this is now available via that variable
     if(that.selectedUrl=="/home"){
      console.log("this.selectedUrlIf",that.selectedUrl)
     }

  });

Explanation: this is a unique variable from the rest (in Object-Oriented Programming). It gets re-assigned to different values (with same name this) based on which function scope it is used. So to keep this to refer to a specific instance inside another function you need to follow one of the approaches above.

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.