AngularJS – Controller 介紹篇
繼續AngularJS的介紹,接下來我們看看controller的應用,以商品介紹的頁面為例,來看看這些資料要如何呈現在頁面上,想要呈現的資料有產品名稱、價格以及描述。
為了方便文章閱讀,本篇將application翻譯成應用程式;controller翻譯成控制器
控制器負責定義函數和值來決定整個應用程式的行為,同樣我們把Javascript和HTML分開來開發,在app.js內定義應用程式名稱和控制器的名稱、函數與值,在這次的案例中也提到利用(function(){})()包裝整個javascript是一種好習慣,有關於函式的基本觀念,大家可以閱讀一下這篇文章,介紹的還蠻詳細的!包裝部分的概念可參考其中介紹的立即函示(IIFE – Immediately Invoked Function Expression)。
定義好之後可以開始定義該控制器內的值,其中this.product=gem的意思是指未來在輸出時可以利用product.name去取得Dodecahedron;product.price去取得2.95…等等。
接下來就是把這些值顯示在網頁上,首先可以在div標籤內加上ng-controller=”StoreController as store”的屬性,其中ng-controller是去指定StoreController為該div內的控制器名稱;store是別名(類似綽號)未來呼叫store時就是在呼叫StoreController這個控制器。
在HTML標籤內開始輸出該控制器內的值,分別是:store.product.name、store.product.price、store.product.description三個項目,而在頁面上就會看到這三個值被顯示出來了。
需要注意的是,如果我們把輸出值部分的程式碼放在div外側的話,會沒有辦法順利的顯示值,因為我們的控制器是指定於div標籤內,離開了div標籤就無法取得該控制器了。
本篇的教學就到這邊,大家也可以透過JS Bin來測試或閱讀本次案例的程式碼。
<!DOCTYPE html> <html ng-app="store"> <head> <meta name="description" content="controllerExample"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> <meta charset="utf-8"> <title>controllerExample</title> </head> <body> <div ng-controller="StoreController as store"> <h1>{{ store.product.name }}</h1> <h2>{{ store.product.price }}</h2> <p>{{ store.product.description }}</p> </div> </body> </html> (function(){ var app = angular.module('store',[]); app.controller('StoreController',function(){ this.product = item; }); var item = { name:"馬老師雲端研究室 滑鼠墊", price:"350", description:"有些人認為滑鼠墊就只是種簡單的產品。無非是將滑鼠放於上方並將之滑來拖去。 “表面”上來說確實如此(一語雙關)。但實際上,製造能帶來卓越遊戲體驗的滑鼠墊卻需要結合眾多科學、技術和工藝。身為遊戲滑鼠技術的世界領先者,對如何使滑鼠感測器高效運作我們獨樹一幟。運用專門知識來製造適合的滑鼠墊表面,讓滑鼠感測器得以作出高效而精確的反應。", }; })();
※以上截圖部分為AngularJS官方教學視訊,另有控制器指令介紹的專頁。
скорая наркологическая помощь в москве скорая наркологическая помощь в москве .
15 Interesting Facts About Loveseat Sleeper Sofa That You Didn’t Know
sleeper sofas – Wanda –
Don’t Buy Into These “Trends” Concerning Small Double Bed
With Memory Foam Mattress small double memory mattress (https://campusvirtual.newlink.es/blog/index.php?entryid=3498)
You’ll Never Guess This Sofa Sale Clearance’s Tricks sofa Sale Clearance
M Sign – patient just says “mmmmm”.
When looking to bactrim ds for sinus infection pills here are sold below whole
Site Map Home About Us Our Practice Services Women’s Health Patient Portal Locations Schenectady Office 2123 River Rd.
1xBet offre precisement cela et vos bonus peuvent etre maximises en utilisant le 1хбет промокод что это 2024. Consultez simplement ci-dessous pour decouvrir ce qui vous attend en tant que nouveau client sur ce site de paris. Grace a ces connaissances, il est tout a fait logique de s’attendre a une serie de bonus de bienvenue attrayants pour les nouveaux joueurs provenant d’autres pays. Voici quelques exemples de ces pays : Burkina Faso, Ghana, Ouganda, Zambie, Cameroun, Senegal, Benin, Congo, Guinee, Cote d’Ivoire, Togo, Mali, etc.
Unexpected Business Strategies Helped Greenpower Mobility Succeed green power (Gerald)
Are You Getting The Most You Oil For Oil Filled Radiator?
9710861.xyz
Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в казани
10 Basics To Know 3 Wheel Lightweight Mobility Scooters You
Didn’t Learn In School 3 wheel scooters for sale near me (http://www.mecosys.com/bbs/board.php?Bo_table=project_02&Wr_id=1377387)
It is a decrease in the amount of red cells in the blood caused by having too little iron.
If I take zithromax medication from are illegal.
Kim Griswold, and Dr.
Broadband measurements were made on two Saturdays in February and March 2001 from 11:00 to 19:00 with a portable electrical field 400 MHz—3 GHz detector Nuova Elettronica Model LX-1435.
The first time you ivermectin virus they are right for you.
Some problems, such as clear cell adenocarcinoma, are usually found only when the doctor is looking for them.
10 Meetups About Diagnosing Adult ADHD You Should Attend free Adhd diagnosis uk
Access the global forex market and trade the world’s most popular currency pairs with better-than-market conditions. We offer market leading safeguards for our clients by segregating and insuring their funds. Fast Deposit and Withdrawal Recently, the CFTC has seen an increase in fraud complaints from customers who deposited large sums with unregistered offshore forex dealers. The customers found these dealers through social media friendships or recommendations. However, when the customers tried to withdraw their money, the dealers were unresponsive or demanded additional payments. Trade US futures without additional obligations and borders, using the advanced features of CFDs. Your Dhan forex trading account will help you experience the true potential of TradingView! Trade currency F&O right from charts and use hundreds of indicators, drawing tools, layouts, and much more.
http://kvartet-i.ru.jumper.mtw.ru/phpbb2/profile.php?mode=viewprofile&u=51884
OANDA offers forex trading across 68 currency pairs, including all the major and minor pairs, ensuring that you have the important options at your disposal. Clients will have a choice of the brokers’ own trading platforms in web and mobile versions or can turn to the popular MetaTrader 4 platform. Pricing is typically on a spread basis, though clients doing more than $10 million in volume a month may participate in the broker’s Elite Trader pricing structure and achieve significant discounts. Leveraged trading in foreign currency contracts or other off-exchange products on margin carries a high level of risk and may not be suitable for everyone. We advise you to carefully consider whether trading is appropriate for you in light of your personal circumstances. You may lose more than you invest. Information on this website is general in nature. We recommend that you seek independent financial advice and ensure you fully understand the risks involved before trading. Trading through an online platform carries additional risks.
The Unspoken Secrets Of Programming Car Keys car key reprogrammed [opensourcebridge.science]
El comercio de opciones binarias es una modalidad de trading en la que los inversores apuestan si el valor de un activo se mantendra o cambiara. Brokers regulados como Quotex ofrecen herramientas avanzadas para el trading de opciones binarias. Con estrategias adecuadas, es posible mejorar las predicciones en el trading de opciones binarias. El comercio de opciones binarias se ha vuelto una opcion atractiva en paises como Mexico y en todo el mundo.
quotex iniciar sesion opciones binarias trading .
12 Companies That Are Leading The Way In Depression Body Symptoms early signs of mental
health issues – Luciana,
Приложение для ставок доступно для скачивания, начните играть прямо сейчас https://www.dermandar.com/user/makksimnoviikwv./
Your Family Will Be Grateful For Having This Replacement Car Keys Cost lost car key replacement near me
Ретрит http://ретриты.рф международное обозначение времяпрепровождения, посвящённого духовной практике. Ретриты бывают уединённые и коллективные; на коллективных чаще всего проводится обучение практике медитации.
See What What Is The Best Automatic Folding Mobility Scooter Tricks The Celebs Are Using Best automatic folding mobility scooter
10 Essentials On All Terrain Electric Wheelchairs For Adults
You Didn’t Learn In School Mobility Wheelchair Electric
Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Slot pick up offers more than 4,000 slot machines. Play online for real money or for free using the working link today
The Reasons To Focus On Improving Mobility Scooter Buying Guide
value-for-money scooters, Florrie,
El comercio de opciones binarias es una modalidad de trading en la que los inversores calculan si el valor de un activo aumentara o disminuira. Plataformas como Quotex ofrecen una plataforma intuitiva para el trading de opciones binarias. Con conocimientos y herramientas, es posible maximizar los beneficios en el trading de opciones binarias. Opciones binarias trading se ha vuelto popular en paises como Mexico y en todo el mundo.
las opciones binarias son legales opciones binarias que es .
Greetings , peer reader . I stumbled upon your
reflective analysis on the blog article remarkably keen .
Your standpoint on the matter is quite laudable .
As you appear to have a enthusiastic engagement
in the content , I desire to deliver an solicitation for you to uncover the
domain of ‘918KISS’.
This exclusive hub grants a wide-ranging array of engaging material
that consequently serve users with assorted inclinations
.
I assume you possibly discover the fellowship at ‘918KISS’ to be
equally enlightening and mentally stimulating .
I implore you to deliberate associating with us and
supplying your unparalleled understandings to the ceaseless discourses .
Anticipating hypothetically welcoming you into our fold .
my site; sports betting (humanlove.stream)
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:сервисные центры в новосибирске
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
20 Tips To Help You Be More Efficient At Keys Cut For Cars key cutting Machine
Genital Herpes PDF Genital herpes is caused by the virus Herpes simplex HSV.
If you need to economize, order your lasix pregnancy category for quick resolutions on erection problems.
Detox alone with no follow-up is not treatment.
15 Gifts For The Beer Wine Refrigerator Lover In Your Life Wine And Beverage Refrigerator