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

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

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

    ReplyDelete
  10. 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
  11. Awesome post. I am glad to see your article. Very interesting to read your article. AWS Certification Course in Chennai

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

    ReplyDelete
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. thanks for sharing nice blog https://duckcreektraining.com/

    ReplyDelete
  28. 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
  29. 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
  30. Great blog wonderful information you have shared thanks for the detailed informative content.
    Techimply

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

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

    ReplyDelete
  35. 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
  36. 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
  37. 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
  38. 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

  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. Thank you for taking the time to publish this very useful information! If you are willing to travel to India, you will need a visa. Apply for an e visa to an Indian online. Do you have any questions regarding e Visa India documents? You can find all frequently asked questions with the answers on eta Indian e visa website. You can also contact the visa support center by phone or by email. Apply for your visa easily and quickly.

    ReplyDelete

  45. 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
  46. 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
  47. You are doing your job very well... I enjoyed everything...Please continue... The person who wants to visit Turkey needs a Turkey e visa to enter the country. The process of Turkish e visa is easy and simple, the application for the e visa of Turkey is easy to fill out for everyone.

    ReplyDelete
  48. 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
  49. 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
  50. 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
  51. This comment has been removed by the author.

    ReplyDelete

Search This Blog