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

87 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. We share this js coding is really helpful to me. And it's this site content is good very useful to me.

    ReplyDelete
  3. 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
  4. Hi Frankcompressors here, Blog is very interesting, thanks for sharing.

    ReplyDelete
  5. 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
  6. 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
  7. 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
  8. Great Content & Thanks For Sharing With oflox. Do You Want To Know How To Make Money From Mitron App

    ReplyDelete
  9. 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
  10. 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
  11. nice Post thanks for the information, good information & very helpful for others.
    Sailpoint Training
    Looker Training
    Oracle Fusion HCM Training

    ReplyDelete
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. Great blog wonderful information you have shared thanks for the detailed informative content.
    Techimply

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

    ReplyDelete
  26. 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
  27. to know more information about AI service desk and help desk for employee. click here : https://bit.ly/3BStWpj

    ReplyDelete
  28. 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
  29. 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

  30. 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
  31. 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
  32. 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
  33. Great blog right here! Also your web site loads up very fast! Hello everyone, Many people ask, what is India e tourist visa, India Tourist e-Visa is an electronic travel permit that every foreign traveler needs to obtain before traveling to India. Foreign nationals from more than 169 countries can apply for a tourist visa India online to enter India.

    ReplyDelete

  34. Wow , there is an excellent conversation about this section here on this site. What is the Vietnam e visa apply online on the web ? It is extremely easy to apply for an e-Visa for Vietnam, which is accessible to inhabitants of 80 nations.

    ReplyDelete
  35. Nice useful post… I am here for the first time and this hit me directly... Data Entry Services play a very vital role in any organization. We provide the best Data entry service in all over the world at an affordable price. The charges of our service fit in any budget. So go and check out the cost and charges.

    ReplyDelete
  36. That is the same thing that I am trying to find. Thanks for sharing this information... The application process of e visa Turkey is easy and simple, the application form of Turkey evisa is easy to fill out for everyone, if you want to apply for visa check out the page.

    ReplyDelete
  37. The International Criminal Police Organization (ICPO; French: Organisation internationale de police criminelle), commonly known as Interpol (UK: /ˈɪnt.ər.pɒl/ INT-ər-pol, US: /-poʊl/ -⁠pohl),[3] is an international organization that facilitates worldwide police cooperation and crime control. Headquartered in Lyon, France, it is the world's largest international police organization, with seven regional bureaus worldwide and a National Central Bureau in all 195 member states.[4]

    Interpol was conceived during the first International Criminal Police Congress in 1914, which brought officials from 24 countries to discuss cooperation in law enforcement. It was founded on September 7, 1923 at the close of the five-day 1923 Congress session in Vienna as the International Criminal Police Commission (ICPC),[5] and adopted many of its current duties throughout the 1930s. After coming under Nazi control in 1938, the agency was effectively moribund until the end of World War II. In 1956, the ICPC adopted a new constitution and the name Interpol, derived from its telegraphic address used since 1946.[6]

    Interpol provides investigative support, expertise, and training to law enforcement worldwide, focusing on three major areas of transnational crime: terrorism, cybercrime, and organized crime. Its broad mandate covers virtually every kind of crime, including crimes against humanity, child pornography, drug trafficking and production, political corruption, intellectual property infringement, and white-collar crime. The agency also facilitates cooperation among national law enforcement institutions through criminal databases and communications networks. Contrary to popular belief, Interpol is itself not a law enforcement agency.

    Interpol has an annual budget of €142 million, most of which comes from annual contributions by member police forces in 181 countries. It is governed by a General Assembly composed of all member countries, which elects the Executive Committee and the President (currently Ahmed Naser Al-Raisi of the United Arab Emirates) to supervise and implement Interpol's policies and administration. Day-to-day operations are carried out by the General Secretariat, comprising around 1,000 personnel from over 100 countries, including both police and civilians. The Secretariat is led by the Secretary-General, currently Jürgen Stock, the former deputy head of Germany's Federal Criminal Police Office.

    Pursuant to its charter, Interpol seeks to remain politically neutral in fulfilling its mandate, and is thus barred from interventions or activities that are political, military, religious, or racial in nature and from involving itself in disputes over such matters.[7] The agency operates in four languages: Arabic, English, French and Spanish.[4]

    ReplyDelete
  38. It’s clearly an exceptional and very useful fact. Thanks for sharing this helpful data with us. CEA Aviation is one of the Best DGCA Ground Classes in delhi. It gives admission to all of the aspirants seeking to start with Ground classes. You can enrol for Best Ground training for DGCA checks with us. Once you're clear with DGCA exam Counsellor Desk will assist you in choosing the best flight academy overseas.

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

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

    ReplyDelete
  41. Looking for a mommy makeover in Hawaii? Face and Body offers a range of cosmetic procedures to help you look and feel your best. Our experienced surgeons are committed to providing top-notch care to ensure your satisfaction. Get started today!

    ReplyDelete
  42. Thanks for this article.
    Graham Builder is the premier home renovation and remodeling contractor in Honolulu. We specialize in kitchen, bathroom, and full-house remodels. Our experienced team of professionals will help you create the ideal space for your home. Contact us today to get started.

    ReplyDelete
  43. If you are looking for a reputable
    Get personal accountant services in Brisbane from Wow! Advisor. Our certified accountants provide tax, business advisory and financial advice tailored to your needs. We offer efficient and reliable assistance to help you achieve your financial goals.

    ReplyDelete
  44. Nice Post! I appreciate you providing this lovely content because it was enjoyable to read and helped me stay informed. Please continue blogging.
    Power BI Training In Hyderabad

    ReplyDelete
  45. This is an excellent initiative! Eliminating global variables in an AngularJS SPA, especially in a Bank App, is a smart move. It not only enhances security but also promotes cleaner, more maintainable code. Kudos for sharing this valuable advice!

    ReplyDelete
  46. Great article! I appreciate you sharing valuable information.
    visit:
    Mulesoft Training In Hyderabad

    ReplyDelete
  47. MuleSoft training is a popular choice for professionals who want to learn how to build and manage integrations. MuleSoft is a leading integration platform that enables businesses to connect any system, data, or API, regardless of its technology stack or location.

    There are many different ways to get MuleSoft training. MuleSoft itself offers a variety of courses, both online and in-person. These courses are designed to teach students the fundamentals of MuleSoft and how to use it to solve real-world integration challenges.

    In addition to MuleSoft's own training courses, there are also many third-party companies that offer MuleSoft training. These companies offer a variety of different course formats,

    ReplyDelete
  48. nice article
    https://careergearup.com/clat-coaching-in-hyderabad/
    https://careergearup.com/sociology-optional-syllabus/
    https://careergearup.com/sociology-optional-coaching-online/
    https://careergearup.com/clat-coaching-in-hyderabad/


    https://careergearup.com/top-10-csat-coaching-institutes-in-hyderabad/

    ReplyDelete
  49. Nice article
    ca coaching in hyderabad
    ca intermediate course
    ca final course
    ca foundation course

    ReplyDelete
  50. Nice article
    cma coaching in hyderabad
    cma foundation course
    cma intermediate course
    cma final course

    ReplyDelete
  51. Your blog post is a mesmerizing exploration of intricate concepts, skillfully combining clarity with profound insights. The seamless integration of well-researched facts and personal perspectives constructs a narrative that captivates and enlightens. Your distinct voice and thoughtful perspective enrich the discourse, ensuring readers experience an engaging and enlightening journey. Eagerly looking forward to more of your exceptional contributions.

    ReplyDelete
  52. About Excellogics
    We are Passionate About Building Excel Tools for the industry
    Ever Wished You Could Do More With Excel? Our Training Can Help You Take Excel To The Next Level. We’re The Team That’s Passionate About Building Excel Tools For The Industry, And We’re Always Working On Something New. Check Back For Updates On Our Blog.

    https://excellogics.co

    ReplyDelete
  53. Perfectly written. Thanks for sharing the article with us!

    Azure Data Factory Training in Hyderabad

    ReplyDelete
  54. "Great article, felt good after reading, worth it.
    i would like to read more from you.
    keep posting more.
    also follow Propmtengineeringcourseinhyderabad"

    ReplyDelete
  55. "Great article, felt good after reading, worth it.
    i would like to read more from you.
    keep posting more.
    also follow Mern Stack course in hyderabad"

    ReplyDelete
  56. This article really struck a chord with me. It beautifully captures the complexity of human emotions and the journey of self-discovery. The way it delves into the intricacies of our thoughts and feelings is truly profound. It's comforting to know that others experience the same struggles and triumphs as I do. This piece reminds me to embrace my uniqueness and cherish every moment of growth. Thank you for sharing such an insightful perspective.

    ReplyDelete
  57. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.
    Flutter Training in Hyderabad

    ReplyDelete
  58. I felt a deep connection to this blog post. The author expressed thoughts and feelings I've often struggled to articulate. Every sentence resonated with my own experiences, making me feel seen and understood. The insights shared are both comforting and thought-provoking. Thank you for sharing your wisdom and giving us all something valuable to reflect on.

    ReplyDelete
  59. I found this blog post incredibly insightful. It’s rare to see such candid reflections on the struggles we all encounter but often keep to ourselves. Your discussion on balancing personal growth with daily life resonated deeply with me. The practical suggestions you provided are both useful and easy to integrate into my routine. Additionally, the personal stories you shared added authenticity and made the advice more relatable. I’m looking forward to reading more of your work; keep it up.

    ReplyDelete
  60. Reading your blog post is like embarking on a spiritual pilgrimage, traversing the landscapes of the mind and soul in search of deeper meaning and understanding. Your words are not just sentences on a page; they are beacons of light illuminating the path towards enlightenment. Thank you for your wisdom, your guidance, and your unwavering commitment to truth.

    ReplyDelete

Search This Blog