Tech Junkie Blog - Real World Tutorials, Happy Coding!: AngularJS SPA : Refactor Code to Not Use Global Variables (Bank App)

Sunday, June 26, 2016

AngularJS SPA : Refactor Code to Not Use Global Variables (Bank App)

In the previous blog post we got AngularJS to work with a module and a controller.  However, we put everything in the global scope.  The problem with that is that there are many JavaScript libraries that might be using the same variables as we are, or if we are working with other developers, there might be some unforeseen conflicts.  The way we can mitigate this problem is to wrap our modules and controllers in an anonymous function.  Think of an anonymous function as a wrapper or a container to hold our modules and controllers.  Another term developers like to refer to anonymous function is an IIFE.  Whatever it's called it's always good practice to avoid putting things in the global environment if it can be avoided.

Here are the steps to take the modules and controllers out of the global environment:

1.  First let's wrap the module in an anonymous function.  The source code for the app.js file should look like the following


(function(){
    'use strict';

    var app = angular.module('bankApp',['bankController']);
    
})();


The code above wraps the application in anonymous function and assigned to the variable call "app"



2.  Now open the "bankController.js" in the "controllers" folder and wrap the "bankController" in anonymous function, the source code for the file should look like the following


(function(){
   'use strict';

angular.module('bankController',[])
 .controller('bankController',["$scope",function($scope){
  $scope.bankAppName="My Bank Application";
}]); 
    
})();


3.  Open up the "index.html" file and make sure the source code looks like the following.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Bank Application</title>
 <link rel="stylesheet" type="text/css" href="app.css">
</head>
<body ng-app="bankApp" ng-controller="bankController">
{{bankAppName}}
<script type="text/javascript" src="js/lib/angular/angular.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/controllers/bankController.js"></script>
</body>
</html>

4.If you open the file you will see that application still works

In this tutorial we've taken some steps to future proof our application so that we are not working in the global environment

98 comments:

  1. Js has really been helpful 🙌🙌 thanks a lot

    ReplyDelete
    Replies
    1. Thank you! I tried to be as clear as possible. Sometimes books can be dry :)

      Delete
    2. Great Article Cloud Computing Projects

      Networking Projects

      Final Year Projects for CSE

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. We share this js coding is really helpful to me. And it's this site content is good very useful to me.

    ReplyDelete
  3. Отличная led лента находится только у Ekodio, даже не сомневайтесь в этом, я лично проверял.

    ReplyDelete
  4. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.

    SAP PP Training in Bangalore

    Best SAP PP Training Institutes in Bangalore

    ReplyDelete
  5. I have recently visited your blog profile. I am totally impressed by your blogging skills and knowledge.

    SAP HANA Online Training

    SAP HANA Classes Online

    SAP HANA Training Online

    Online SAP HANA Course

    SAP HANA Course Online

    ReplyDelete
  6. Hi Frankcompressors here, Blog is very interesting, thanks for sharing.

    ReplyDelete
  7. I recently visited your blog profile. I was really impressed with blogging skills and knowledge.
    Vist our website too, We are Screw Dilator suppliers.



    ReplyDelete
  8. Really amazing experience to visit your blog, thanks a lot for sharing with us. Visit Ogen Infosystem for creative website designing and ppc services at best price in Delhi.
    Web Designing Company

    ReplyDelete
  9. Water bodies are the main source of transportation for international freight forwarding. Due to this, sea freight company in Delhi,
    visit
    Freight Forwarder in Vietnam
    Shipping Company In India

    ReplyDelete
  10. If you know so much about code, Why don't you start youtube channel about it? Now is very easy to get youtube subscribers. Just go to this site https://soclikes.com/buy-youtube-subscribers and buy. That is all

    ReplyDelete
  11. Great Content & Thanks For Sharing With oflox. Do You Want To Know How To Make Money From Mitron App

    ReplyDelete
  12. I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively. ExcelR Data Science Course In Pune

    ReplyDelete
  13. When I study programming I read this post https://blog.nus.edu.sg/sarkar/how-to-become-a-tiktok-star-while-studing/ and start my tiktok blog. How I grateful to author of this post. Tiktok is the most lovely thing in my life and I have great results there

    ReplyDelete
  14. Nice to read your article. This has really made good thing.

    Perl training in bangalore

    ReplyDelete
  15. Awesome post. I am glad to see your article. Very interesting to read your article. AWS Certification Course in Chennai

    ReplyDelete
  16. Awesome post. I am glad to see your article. Very interesting to read your article. AWS Certification Course in Chennai

    ReplyDelete
  17. เราคือผู้นำด้านเกมพนันออนไลน์ Major168 เราคือผู้ให้บริการ คาสิโนออนไลน์ ที่ได้รับรองว่าดีที่สุดในประเทศไทย มีค่ายเกมส์ให้เล่นมากมาย Sagaming, Sexy bacarat, Dreamgame, Ebet, Wm casino, Vivo gaming ไม่ผ่านเอเย่นต์ ระบบปลอดภัยมีทีมงานดูแลตลอด 24ชม.

    SAGAME88 แหล่งรวมเกมส์พนันออนไลน์ คาสิโนสด บาคาร่า กำถั่ว คาสิโนออนไลน์ ไฮโล รูเล็ต รับเครดิตฟรีเล่นได้ทุกเกมส์ โบนัสสมาชิกใหม่เพียบ พร้อมระบบฝากถอนออโต้ 10วิ เรามีทุกค่ายเกมส์ให้คุณเลือกเดิมพัน SA Game Sexy bacarat Dreamgame WM Casino VIVO Gaming Ebet เล่นได้ทุกเกมส์

    Our website ufabet provides betting services in the system of Auto Deposit-Withdrawal. Our members are not only in Thailand. Online football betting UEFA Bet market And this makes a guarantee that Ufabet168 is another reliable football betting website

    ufa through the website UFABET1688 a web gambling online , one that integrated all the bets from online casinos , online casino , online , and also have a game a lot more to be chosen to play such games.

    ReplyDelete
  18. Online football betting ufabet will definitely get the price of water more than anywhere else. When compared with other companies such as other water 1.90, we water 1.94 or more, depending on the pair. We guarantee the price of 4 sets of football betting with us, starting with a minimum of only 10 baht, because our website has no minimum deposit with an automatic system

    ReplyDelete
  19. nice Post thanks for the information, good information & very helpful for others.
    Sailpoint Training
    Looker Training
    Oracle Fusion HCM Training

    ReplyDelete
  20. Thanks for sharing this informative content.,
    Leanpitch provides online training in Scrum Master Certifiation during this lockdown period everyone can use it wisely.
    Join Leanpitch 2 Days CSM Certification Workshop in different cities.

    Scrum master certification online

    CSM certification online

    ReplyDelete
  21. Thanks for sharing this.,
    Leanpitch provides crash course in Brain hacks using NLP everyone can use it wisely.

    Brain hacks with NLP

    NLP training

    ReplyDelete
  22. Thanks for sharing this.,
    Leanpitch provides crash course in Brain hacks using NLP everyone can use it wisely.
    NLP training

    NLP crash course

    ReplyDelete
  23. You have described it so deeply. Every normal person can easily understand how a data network works. But some people mix it with data center. Fungible ​is a company that is providing the best data center solution. From that website, you can easily understand what is data center.

    ReplyDelete
  24. Thanks for sharing this.,
    Leanpitch provides online training in A-CSPO during this lockdown period everyone can use it wisely.
    Join Leanpitch 2 Days A-CSPO Certification Workshop in different cities.

    a-cspo certification
    a-cspo training

    ReplyDelete
  25. I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one website management

    ReplyDelete
  26. I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post. ppc management

    ReplyDelete
  27. Awesome article with great information provided by your article, here I would like to thank you guys for sharing such a fantastic blog. Regards digital marketing

    ReplyDelete
  28. toptan iç giyim tercih etmenizin sebebi kaliteyi ucuza satın alabilmektir. Ürünler yine orjinaldir ve size sorun yaşatmaz. Yine de bilinen tekstil markalarını tercih etmelisiniz.

    Digitürk başvuru güncel adresine hoşgeldiniz. Hemen başvuru yaparsanız anında kurulum yapmaktayız.

    tutku iç giyim Türkiye'nin önde gelen iç giyim markalarından birisi olmasının yanı sıra en çok satan markalardan birisidir. Ürünleri hem çok kalitelidir hem de pamuk kullanımı daha fazladır.

    nbb sütyen hem kaliteli hem de uygun fiyatlı sütyenler üretmektedir. Sütyene ek olarak sütyen takımı ve jartiyer gibi ürünleri de mevcuttur. Özellikle Avrupa ve Orta Doğu'da çokça tercih edilmektedir.

    yeni inci sütyen kaliteyi ucuz olarak sizlere ulaştırmaktadır. Çok çeşitli sütyen varyantları mevcuttur. iç giyime damga vuran markalardan biridir ve genellikle Avrupa'da ismi sıklıkla duyulur.

    iç giyim ürünlerine her zaman dikkat etmemiz gerekmektedir. Üretimde kullanılan malzemelerin kullanım oranları, kumaşın esnekliği, çekmezlik testi gibi birçok unsuru aynı anda değerlendirerek seçim yapmalıyız.

    iç giyim bayanların erkeklere göre daha dikkatli oldukları bir alandır. Erkeklere göre daha özenli ve daha seçici davranırlar. Biliyorlar ki iç giyimde kullandıkları şeyler kafalarındaki ve ruhlarındaki özellikleri dışa vururlar.

    ReplyDelete
  29. Sankey Visualization is the best visualization to improve your SEO. Sankey diagram is a very useful visualization to show the flow of data.ChartExpo provides you a better and easiest way to create the Sankey Diagram in no time without coding only on few clicks. Read more here : https://ppcexpo.com/blog/visualizing-customer-journey-with-sankey-diagram .

    ReplyDelete
  30. Fantastic goods article.I understood your stuff before and you are great..Turkey travel visa and visa required for Turkey, you need to fill visa application form Turkey online through Turkey e visa.

    ReplyDelete
  31. Hi, I want to subscribe for this blog to get most up-to-date updates, so where can i do it please help out. 카지노
    (mm)

    ReplyDelete
  32. Thank you for this post. The international tourists who want to apply for Azerbaijan sticker visa must check the Azerbaijan sticker visa requirements online.

    ReplyDelete
  33. Attractive component of the material. I just stumbled across your web site and accession capital to say that I really enjoyed your site. With just a few clicks, foreign nationals can apply for a Kenya online visa application from their home. Fill the form with accurate and complete information about the passenger's data.

    ReplyDelete
  34. FNP Gardens is a unit of Ferns N Petals that offers a range of wedding venues and banquet halls in Delhi and Gurgaon. The beautiful venues offer all amenities to host elegant weddings, as well as pre-wedding and post-wedding functions. FNP Gardens offer a combination of spaces that includes both indoor and outdoor wedding venues. The farmhouses are known for their aesthetically designed lush green spaces, understated elegance as well as excellent hospitality services. All the venues have their own uniqueness and are designed differently from each other to which makes them popular amongst other banquet halls in Delhi and Gurgaon for weddings. The following list highlights all the Gardens: The Ritz, The Riviera, The Riviera House, Shagun Farms, Chattarpur Central, Pavilion, Opulent Hotel, Udman, Vilasa, The Kundan. These venues are noted as one of the top banquet halls in Delhi for offering the best services for any kind of event

    wedding venues in delhi
    banquet halls in gurgaon
    banquet halls in south delhi
    wedding venues in chattarpur
    banquets in west delhi
    wedding venues in greater noida
    Sarai Kale Khan Cremation Ground

    ReplyDelete
  35. This is really a good article. The Government of Ukraine grants the e-visa online. Do you have any idea about the Ukraine visa fees?. The Ukraine visa fee is dependent on your nationality and type of visa.

    ReplyDelete
  36. Amazing post…. Travelers from around 169 countries can now apply for an online Indian visa application with 1 month, 5 years validity of 1 year.Travelers can opt for double or multiple entry, depending on the validity of the visa.

    ReplyDelete
  37. This is a wonderful inspiring article. I am practically satisfied with your great work. You have really put together extremely helpful data. Keep it up.. kenya business visa allows several foreign nationalities to enter Kenya for business ventures.

    ReplyDelete
  38. thanks for sharing nice blog https://duckcreektraining.com/

    ReplyDelete
  39. I'm writing on this topic these days, 메리트카지노, but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts.


    ReplyDelete
  40. I definitely enjoy every little bit of it and It is a great website. I want to thank you for the content. I learn a lot from your blog. Good job! You guys do a great blog and have some great content. Keep up the good work.
    Best School Management Software

    ReplyDelete
  41. Great blog wonderful information you have shared thanks for the detailed informative content.
    Techimply

    ReplyDelete
  42. Wow.. Very informative article thanks for sharing please keep it up.. Pakistan visa fees depend on your visa type and nationality.

    ReplyDelete
  43. I definitely enjoy every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep it up
    top crm software

    ReplyDelete
  44. Nice post. I love to keep up the good work. e business visa India, The Indian business visa application form can be completed from home online via India e visa portal.

    ReplyDelete
  45. to know more information about AI service desk and help desk for employee. click here : https://bit.ly/3BStWpj

    ReplyDelete
  46. When I get to meet people with expertise, many of them with PhDs, others straight from top universities for business, I can see an air of confidence in their posture. It's a confidence that someone who comes from an humble background or with no formal education might not possess. In most cases when we begin to talk about knowledge, the aura disappears. What fascinates me is how the formal structure of education have stifled their curiosity. However I have met people from remote villages -who are full of enthusiasm as well as creativity and innocence.

    ReplyDelete
  47. Your writing and explanations are very impressive. Your article is very informative. five years Indian e tourist visa, You can apply online for a 5 years Indian e tourist visa via Indian visa website.

    ReplyDelete
  48. Definitely enjoyed every bit of it. This is a good website and the items are of high quality. Thank you so much. Indian visa from USA, US citizens can apply online via India E Visas website.

    ReplyDelete
  49. I like your post. I appreciate your blogs because they are really good. Please go to this website for Data Science course in Bangalore. These courses are wonderful for professionals.

    ReplyDelete
  50. The website is good and the stock is good. Thanks for all you do. apply for Indian visa online. It's too easy , fast and secure.It is called an electronic visa India system.

    ReplyDelete
  51. Hii everyone, Thanks for sharing. Do you know what Indian visa photo requirements are? You can read India visa photo requirements on our indian visa website. We explained all details related to the India visa photo on our page.


    ReplyDelete

  52. Hii friends, this is great. If you want to learn more about Turkish e visa you can visit our Turkey e visa website. And read here all info about Turkey visa online.

    ReplyDelete
  53. Brilliant! Incomprehensible article man! Thanks, although I ran into problems with your RSS feed. I can't appreciate the inspiration why I can't do this. Are there other people with similar problems with RSS? Can you answer all the individuals who have the right answer? Highly valued !!
    Visit viral times for tech news.

    ReplyDelete
  54. Good afternoon everyone, Do you know about the Indian visas? Tourists can now apply for a visa for India or eVisa for India. In 5 to 10 minutes you can fill your application form online through Indian Visa Portal. And you can read more information about Visa on our India Visa Blog.



    ReplyDelete
  55. This is also a very good post which I really enjoyed reading. It's not every day that I'm likely to see something like this. You can fill your Indian business visa application form online within 5 to 10 minutes and then pay India business visa cost online.

    ReplyDelete

Search This Blog