Thursday 18 April 2013

AngularJS Directives and Isolate Scope

I've been learning the AngularJs framework recently and have come across a case study that highlights how Isolate Scope works.

The app we're developing needs two individual sliders. The values represented by each of the sliders are related as they form two variables in a simple equation: the Loan-to-value ratio of a mortgage (LTV). The LTV is a percentage of the Loan Required figure over the Property's Value figure. There is a slider for both the Loan Required and Property Value.

Currently, mortgage lenders are reluctant to offer mortgages with an LTV over 95%. We've therefore chosen to introduce this feature into our sliders, so that they may not be dragged to a position in which the LTV ration is greater than 100%. If a slider is dragged beyond the 100% mark, the other slider must be moved accordingly so as to maintain the ratio at 100%. Challenge accepted.

This seemed like a good fit for a Directive. A Directive in AngularJs is a way of describing a portion of the page. Using a directive to construct your page is what's known as being declarative. Your intentions for the purpose of that piece of mark up is clear. A Directive would be something that you might use often, so as to provide yourself with a short hand way of getting the element on the page.

We intend to create a 'Linked Slider' Directive, that is capable of communicating with other slider directives, so that their values may stay in-sync. To do this we must make use of Isolate Scope. Scope is very important in AngularJs. It is the 'glue' that allows controllers and views to share information. The Angular Magic permits us to manipulate the same values in both the controller and the view - its the Scope that keeps the values consistent across both, thus delivering a huge amount of value for developers.

Scope is normally associated with a Controller and a View. Directives are declared on the View and share the same Scope as the Controller and View. Isolate Scope enables the Directive to maintain its own Scope. This is useful for us for two reasons. Firstly, it gives us the ability to 'wire up' our directive to our outer Scope without tightly coupling it - making it reusable elsewhere. Secondly, it allows us to have multiple instances of the same slider Directive.

You might enjoy the working example to get a feel for what I'm talking about. The code for the directive is shown below, followed with discussion..


Starting from line 1, the directive is declared on the app global variable, and named as 'linkedSlider'. It is restricted for us as an attribute (A), and then has its Scope defined.

The Scope property is the Isolate Scope I was banging on about. There is a convention at play here. The keys of the scope property become attributes that can be used to configure the Directive when it is declared in the mark up. The '=', '@' and '&' values of these keys have special meaning.

'=' means the value is a two-way binding property. This means that its value can be changed by the Directive and by the Controller. This is why we use the '=' symbol to describe both the Value and Link properties. The Value property is the value that the slider is going to maintain. The Link property is the value that the slider is going to have to update in light of changes to its own Value when the LTV is pushed over 100%. It is this arrangement that lets us declare the property once and but be able to use it as many sliders as we like.

'@' is a straight forward attribute. It does not stay up to date in the Directive if it is changed in the Controller's scope. For this reason attributes are normally populated with string literals or numeric values. In our case, we specify all the necessary properties of the slider (max, min & step).

'&' represents an expression to be evaluated. It could be a pointer to a function on the Scope, or anything that can be executed. I have used this type of scope property to contain the test to be checked each time the slider is moved, to determine whether or not the other slider needs to be adjusted.

The Link function that follows is what binds the directive to the controller and kicks everything off. You will notice still the reliance on jQuery to create an instance of the jQuery UI slider. Nothing unusual there. As you can see I pass in the necessary configuration from the Isolate Scope of the instance of the Directive. When the slide event occurs, I have to call the special function scope.$apply() for the value change to be recognised in the Controller Scope. I then evaluate the Scope's condition property (remember that we defined it as an expression with '&') to find out if the new value would cause the LTV to exceed 100%. If so, I use the scope.$apply function again to update the Link property value in the Controller Scope.

As we have just seen, we have given our Directive the ability to change the value of it's Link property. This Link property will be a Value property in another instance of the same Directive, so we need to be able to listen for changes. scope.$watch is just the thing we need to be able to react to changes to our Value in the Controller Scope. When a change occurs, we use the jQuery UI slider API to update our slider's value, this also takes care of dragging the slider to the correct position.

There still remains two unexplained features for the moment. I do not understand why a setTimeout is required. Without it, the attribute ('@') values are not yet populated at the time of initialising the JQUI Slider. Also, I am also required to apply a scope.$watch to the Link value. Again, without this the Link property value will not stay up to date, even though there is no actual function content. A small price to pay for what is otherwise an elegant (enough) solution.


111 comments:

  1. Best Angularjs Training Chennai. Angularjs training is essential for developing any single page web application. You have learn Angularjs indepth to creating enterpirse SPA application.

    Angularjs Training
    Angular.js Course
    Angularjs Online Training
    Angularjs Training in Chennai

    ReplyDelete
  2. Come and read us!! We are moving our blog into a new site with a much more pretentious goal. We are going to teach how to be AngularJS Ninjas!!! That's right! We have taken a couple of weeks to prepare our first workshop, absolutely free!!!!


    AngularJS Training in Chennai
    AngularJS Training Institute in Chennai

    AngularJS Certification Training in Chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi admin this is one of the wonderful blog that i read.Igather lot of information in this blog. Thanks for sharing this kind of useful blog.Anybody want to learn
    Angularjs Online Training

    ReplyDelete
  5. It's very nice blog. I'm so happy to gain some knowledge from here. Thank you for valuable information on
    AngularJS Training in Chennai.
    Hoping to get more info...

    ReplyDelete
  6. It's good to see this blog to learn something. check it once through Angularjs Online Training Bangalore

    ReplyDelete
  7. The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents...Great job, keep it up..
    Hire angularjs developers

    ReplyDelete
  8. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @ https://www.australiabesttutor.com




    Our Services

    Online assignment help Australia
    my assignment help Australia
    assignment help
    help with assignment
    Online instant assignment help
    Online Assignment help Services

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Each department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.

    AutoCAD training in Noida

    AutoCAD training institute in Noida


    Best AutoCAD training institute in Noida

    ReplyDelete
  11. Thank a lot for this post that was very useful.keep sharing
    angularjs online training in hyderabad

    ReplyDelete
  12. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Blueprism training in btm

    Blueprism online training

    AWS Training in chennai

    ReplyDelete

  13. Like different elements of India, numerous oil and spices usually cross into making food. This effects in substances getting caught to the partitions of the filter out.
    Visit here
    http://kitchenware.ml
    Best kitchen chimney installation and service
    Auto clean chimney sevice in Faridabad

    ReplyDelete
  14. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    AWS Interview Questions And Answers

    AWS Training in Chennai | Best AWS Training in Chennai


    AWS Training in Pune | Best Amazon Web Services Training in Pune

    AWS Tutorial |Learn Amazon Web Services Tutorials |AWS Tutorial For Beginners

    ReplyDelete
  15. I’d love to be a part of group where I can get advice from other experienced people that share the same interest. If you have any recommendations, please let me know. Thank you.
    iosh course in chennai

    ReplyDelete
  16. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  17. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
    Keep update more information..


    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete
  18. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information regarding Microsoft Azure which is latest and newest,

    Regards,
    Ramya

    azure training in chennai
    azure training center in chennai
    best azure training in chennai
    azure devops training in chenna
    azure training institute in chennai

    ReplyDelete
  19. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  20. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this.Also Checkout: blockchain technology training chennai | blockchain training institute in chennai | best blockchain training in chennai | blockchain certification training in chennai

    ReplyDelete
  21. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    SEO company in coimbatore
    SEO Service in Coimbatore
    web design company in coimbatore

    ReplyDelete
  22. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    Check out :
    hadoop training in Chennai |
    big data training in chennai |
    big data hadoop training in chennai |
    big data training and placement in chennai

    ReplyDelete
  23. Excellent article, nice info, must say thanks for the information you added to this post. I appreciate your post and looking forward for more.


    Data Science Courses Bangalore

    ReplyDelete
  24. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!




    DATA SCIENCE COURSE MALAYSIA

    ReplyDelete
  25. Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate

    DevOps Training in Chennai
    Splunk Training in Chennai

    ReplyDelete
  26. It is one of the wonderful blog i have read.Keep Posting good articles like this

    DevOps Training in Chennai
    Splunk Training in Chennai

    ReplyDelete
  27. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.data science course in singapore

    ReplyDelete
  28. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article. I appreciate your post and look forward tomorrow.data science course in singapore

    ReplyDelete
  29. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article. I appreciate your post and look forward tomorrow.data science course in singapore

    ReplyDelete
  30. Really very happy to say,your post is very Awesome to read.I never stop myself to say something about it.You’re doing a Great job.keep it up
    www.bexteranutrition.com
    www.digital marketingfront.com
    designing info.in
    www.https://www.hindimei.net

    ReplyDelete
  31. Really very happy to say,your post is very Awesome to read.I never stop myself to say something about it.You’re doing a Great job.keep it up
    www.bexteranutrition.com
    www.digital marketingfront.com
    designing info.in
    www.https://www.hindimei.net

    ReplyDelete


  32. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog,i want to share some Information about splunk tool tutorial . keep updates regularly..

    ReplyDelete
  33. I would like to say thank you for the amazing details and concepts you are sharing in this.The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! to read. I never stop myself to say something about it. You’re doing a great job. Keep it up...



    Microsoft Windows Azure Training | Online Course | Certification in chennai | Microsoft Windows Azure Training | Online Course | Certification in bangalore | Microsoft Windows Azure Training | Online Course | Certification in hyderabad | Microsoft Windows Azure Training | Online Course | Certification in pune


    ReplyDelete

  34. This post is really helpful for us. I certainly love this website, keep on it.
    Data Science Course in Hyderabad

    ReplyDelete
  35. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. After reading your article I was amazed. Data Science Training In Chennai | Certification | Data Science Courses in Chennai | Data Science Training In Bangalore | Certification | Data Science Courses in Bangalore | Data Science Training In Hyderabad | Certification | Data Science Courses in hyderabad | Data Science Training In Coimbatore | Certification | Data Science Courses in Coimbatore | Data Science Training | Certification | Data Science Online Training Course


    ReplyDelete
  36. Thank you for sharing such a really admire your post. Your post is great!
    data science course in Hyderabad

    ReplyDelete
  37. Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.Thanks for sharing this wonderful content.its very useful to us.I gained many unknown information, the way you have clearly explained is really fantastic.
    DevOps Training in Chennai

    DevOps Online Training in Chennai

    DevOps Training in Bangalore

    DevOps Training in Hyderabad

    DevOps Training in Coimbatore

    DevOps Training

    DevOps Online Training

    ReplyDelete
  38. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training


    ReplyDelete
  39. http://www.rockfishsec.com/2015/05/gpu-password-cracking-with-amazon-ec2.html?showComment=1597631106637#c2238429256893842664
    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  40. The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents...Great job, keep it up..


    AWS Course in Chennai

    AWS Course in Bangalore

    AWS Course in Hyderabad

    AWS Course in Coimbatore

    AWS Course

    AWS Certification Course

    AWS Certification Training

    AWS Online Training

    AWS Training

    ReplyDelete
  41. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    Simple Linear Regression

    Correlation vs covariance

    KNN Algorithm

    ReplyDelete
  42. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  43. Good job admin.This blog is very use for the people who reads and give usefull information which they needed. Keep doing more good jobs. Good Luck.
    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  44. I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
    Data Analytics Course in PuneWow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also.
    I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…

    ReplyDelete
  45. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    Simple Linear Regression

    Correlation vs Covariance

    bag of words

    time series analysis

    ReplyDelete
  46. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge so keep on sharing such kind of an interesting blogs.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  47. wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated.
    Data Science Training

    ReplyDelete


  48. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us.
    Best Institute for Data Science in Hyderabad

    ReplyDelete
  49. This is an awesome motivating article.I am practically satisfied with your great work.You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to perusing your next post
    data scientist training in hyderabad

    ReplyDelete
  50. Software Development Engineer Training SDET is an emerging role in the present scenario, this role needs an IT professional that can handle development as well as testing effectively. The entire software development process is handled from developing to the testing phase. So this role has high priority in the industries.

    ReplyDelete
  51. Very nice job... Thanks for sharing this amazing and educative blog post!
    data science training in malaysia

    ReplyDelete
  52. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post.Keep up your work
    data science course in malaysia

    ReplyDelete
  53. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    machine learning course in noida

    ReplyDelete
  54. I am truly getting a charge out of perusing your elegantly composed articles. It would seem that you burn through a ton of energy and time on your blog. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome.
    data scientist training in hyderabad


    ReplyDelete
  55. I am visiting first here. Really an awesome content and informative blog. Keep up this good work.
    Data Science Course Training in Hyderabad

    ReplyDelete
  56. I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website. data scientist course in kanpur

    ReplyDelete
  57. Специфический список мероприятий, направленных на предположение линии жизни, называют хиромантия. Гадание на картах Таро на мужа - это простой способ поворожить с употреблением разнообразных атрибутов и методов. Магические силы и многообразные обстоятельства ворожения наукой не описаны, при том многие люди верят в это.

    ReplyDelete
  58. Are you looking for the best Data Science course institute that will aid you in growing in your career. 360DigiTMG is the place for you. Start your course today!business analytics course in rohtak

    ReplyDelete
  59. Hi, Thanks for such a fantastic blog. I have gone through your post and I found it so amazing and interesting. Keep it up and keep sharing such posts.

    The Competency Performance Report (CDR) is a document indicating that your engineering skills and knowledge meet Australian standards. Engineers Australia (EA) evaluates your CDR before deciding whether you qualify for the occupational category you are applying for, which in turn is the basis for approving your Australian immigration.

    Need writing help to submit assignments on time? Get the Best CDR Writing Help from our Ph.D.-level experts in Australia at Reasonable Prices. Their knowledge of CDR Assignments will help you to get good grades.
    EXPERTISE IN:
    Engineering Assignment Help,
    Pay for Assignment,
    Etc.
    BEST IN PRICE - 24*7 ONLINE SUPPORT

    ReplyDelete
  60. Get Data Science Certification from top-ranked universities UTM, Malaysia, and IBM. We provide extensive training for the future-ready workforce.
    data science training in malaysia

    ReplyDelete
  61. Thank you for sharing. Greetings! I'm a trusted tech wizard when it comes to AOL Email not working issues. If you're frustrated with glitches or errors in your AOL email, worry no more! I'll dive into the problem head-on, swiftly troubleshoot and resolve any issues that hinder your communication. Rest assured, I'll get your AOL email up and running smoothly.

    ReplyDelete
  62. What a nice post! I'm so happy to read this. What you wrote was very helpful to me. Thank you.
    Please go to my website: Medsvilla.com
    Allow yourself to be carried away by your passion. Cenforce 150mg is a prescription-only medicine. Sildenafil Citrate is a medicine that is used to treat the condition, impotence, and premature ejaculation in men. The fact that this medication functions just like Viagra is its best feature. The only distinctions between generic and branded versions are, of course, the brand name and the manufacturers. Many more medicines like Cenforce 200 | Vidalista 40 you can buy from our site.

    ReplyDelete
  63. Fildena Tablets is a prescription drug and should only be taken under the guidance of a doctor. It can cause side effects that range from mild to severe depending on how the body reacts to the medication. Some of the most common side effects include headache, flushing, indigestion, and dizziness. If you experience any of these side effects, contact a doctor immediately. Fildena 100 vs viagra can also cause a sudden increase in blood pressure and should not be taken by anyone who has an existing heart condition or high blood pressure.

    ReplyDelete
  64. Greetings of the day. My name is Emily Griffin, I have 7 years of work experience as a professional technical engineer. Are you facing the quicken online service unavailable ? Do not hesitate to contact us to continue your error-free financial journey.

    ReplyDelete
  65. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    Cenforce 200 and Cenforce 150mg is a brand of medication that contains sildenafil citrate as its active ingredient. Sildenafil citrate is a phosphodiesterase type 5 (PDE5) inhibitor commonly used to treat erectile dysfunction (ED) in men. Vidalista 40 tablets were created exclusively for men to treat erectile dysfunction (ED) or impotence. The principal active element in this drug, sildenafil, improves blood flow to the penis. our site Medsvilla.com where you can get more information about it.

    ReplyDelete
  66. The article which is given here is very nice and helpful information. Congratulations on your brilliant success. If you are a students and looking help for dissertation abstract then you can visit here: Dissertation Abstract Help Services

    ReplyDelete
  67. Take Cenforce 100mg approximately 30-60 minutes before engaging in sexual activity. This allows the medication sufficient time to take effect, ensuring optimal performance.

    Sexual Arousal is Key: While Cenforce 100mg facilitates the physiological processes necessary for an erection, sexual arousal remains a crucial component for its effectiveness.

    Visit here: Cenforce 120mg

    ReplyDelete
  68. This comment has been removed by the author.

    ReplyDelete
  69. Enrolling in Brolly AI's Generative AI course is not just an investment in education—it's an investment in your future. Whether you're seeking to unlock new career opportunities, differentiate yourself in the job market, or pursue entrepreneurial ventures, this course provides the knowledge, skills, and networking opportunities you need to succeed in the dynamic and rapidly evolving field of AI.
    generative ai training in hyderabad

    ReplyDelete