AngularJS – Directive 介紹篇
接續前面提到的關於產品展示頁面的製作,我們在HTML文件上面加入一個Add to Cart的按鈕,但是希望這個按鈕可以有條件性的顯示或隱藏,我們可以在該按鈕的HTML標籤中加入ng-show=”store.product.canPurchase”的屬性,這個屬性會去判斷在gem數列中canPurchase中的值是否為true,若不是則該按鈕不顯示於畫面上,反之則會顯示加入購物車(Add to Cart)的按鈕。
在這個案例中canPurchase就算是在數列中的顯示參數,其實這個參數並不是一定要叫canPurchase這個名稱,可以自行決定名稱,例如在馬老師製作的案例中,我就是利用buttonShow這樣的參數名稱,大家也可以在JS Bin上面看看這個案例的程式碼。
<!DOCTYPE html> <html ng-app="store"> <head> <meta name="description" content="AngularJS directivesExample 1"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> <meta charset="utf-8"> <title>AngularJS directivesExample 1</title> </head> <body> <div ng-controller="StoreController as store"> <h1>{{ store.product.name }}</h1> <h2>NT${{ store.product.price }}</h2> <p>{{ store.product.description }}</p> <button ng-show="store.product.buttonShow">加入購物車</button> </div> </body> </html> (function(){ var app = angular.module('store',[]); app.controller('StoreController',function(){ this.product = item; }); var item = { name:"馬老師雲端研究室 滑鼠墊", price:"350", description:"有些人認為滑鼠墊就只是種簡單的產品。無非是將滑鼠放於上方並將之滑來拖去。 “表面”上來說確實如此(一語雙關)。但實際上,製造能帶來卓越遊戲體驗的滑鼠墊卻需要結合眾多科學、技術和工藝。身為遊戲滑鼠技術的世界領先者,對如何使滑鼠感測器高效運作我們獨樹一幟。運用專門知識來製造適合的滑鼠墊表面,讓滑鼠感測器得以作出高效而精確的反應。", buttonShow: false }; })();
另外還有一種資料顯示的手法,我們可以在gem數列中另外加入soldOut這個參數,而在div的HTML標籤中加入ng-show=”!store.product.soldOut”這樣的屬性,其中驚嘆號指的是不等於,所以這個屬性的意思即是當soldOut參數不等於true的時候要隱藏該div,也就是會隱藏所有的商品資訊。
不過這樣的表達方式並不是很直接,必須要做邏輯上的轉換,因為條件式是soldOut不等於true就顯示該商品,不是很容易搞懂,所以同樣的案例我們可以把HTML中的標籤的屬性改成ng-hide=”store.product.soldOut”,這樣一來我們只需要去看soldOut參數中的值是true或是false,如果賣完就不顯示;沒賣完就顯示,這是一個比較直覺的方法,透過JS Bin觀賞本案例的原始碼。
接下來看多項商品的製作方式,首先必須了解如何在Javascript的數列中加入多項商品的資料。
輸入了以上數列的資料後,在HTML的頁面上可以依下圖的方式呈現出多重商品的資訊,不過從以下的呈現方式可以看的出來,如果商品數量不僅僅是只有兩項,那頁面上面的HTML標籤就會過於複雜,所以下面的方法僅僅是讓大家了解邏輯的部分。
實際上呈現的方式可以參考下圖,是不是簡單多了,在JS Bin上面觀看。
接下來幫大家整理目前講解到的一些AngularJS的專有名稱說明:
- Directives(指示) – 在HTML中觸發Javascript行為的參數。
- Modules(模組) – 定義我們的應用程式。
- Controllers(控制器) – 定義我們應用程式該如運作。
- Expressions(表達式) – 我們的資料該如何的顯示在頁面上。
※以上截圖部分為AngularJS官方教學視訊,另有directive指令介紹的專頁。
Woh I like your content , saved to bookmarks ! .
some truly interesting info , well written and broadly speaking user genial .
After study a few of the blog posts for your web site now, and i also genuinely as if your method of blogging. I bookmarked it to my bookmark site list and will also be checking back soon. Pls check out my web page also and tell me what you consider.
Awesome read , I’m going to spend more time researching this topic
Spot on with this write-up, I really believe this site needs much more attention. I’ll probably be returning to see more, thanks for the advice!
Отличный сайт! Всем рекомендую!пиастрикс казино
This information is bit incomplete, I must say that the homework was done fantastic, perhaps the biggest issue emerged if you experimented with build this information and also offer the item. Undoubtedly took action now your easiest and i get pleasure from the point that this will help too, you ought to study alternative posts in addition to create your own posting definitely concise plus definitely comprehensible. I will Pm anyone a lot of the strings concerning this theme so that the when people go to forum along with article something genuinely educational similar to this, it’s going to be more potent and beneficial to all.
Отличный сайт! Всем рекомендую!Пиастрикс
Spot on with this write-up, I truly assume this web site needs way more consideration. I’ll most likely be again to read rather more, thanks for that info.
Отличный сайт! Всем рекомендую!Piastrix
Очистка воды имеет большое значение в сохранении безотказной работы промышленного оборудования – https://vodoclean.ru/cirkuljacionnyj-nasos-aquario-14-14-50f.html. Процесс включает в себя фильтрацию и настройку воды для удаления загрязнений, таких как растворённые соли, органические вещества и микроорганизмы. Это обязательно для избежания разрушения, наслоений и других проблем, которые могут ухудшить производительность оборудования и снизить долговечность. Применение качественной водоподготовки позволяет не только увеличить надёжность и срок службы оборудования, но и снизить затраты на его обслуживание и техническое обслуживание.
Современные системы водоподготовки содержат большое количество технологических шагов и техники. Среди них важно отметить фильтрационные установки, используемые для удаления крупных частиц, обратноосмотические системы, которые качественно устраняют солевые элементы, и ультрафиолетовые установки, убивающие бактерии. Также важно отметить химические реагенты, используемые для корректировки pH и борьбы с коррозией. Автоматизация процесса существенно улучшает эффективность и производительность процесса водоподготовки, что крайне важно в условиях большого производства.
Эффективная водоподготовка положительно влияет на экологическое состояние, снижая выбросы вредных соединений в природную среду. Использование передовых технологий и устройств позволяет минимизировать потребление воды и её загрязнённость, что совпадает с целями устойчивого развития. Промышленные предприятия, обращающие внимание на водоподготовку, не только улучшают свои результаты, но и демонстрируют ответственное отношение к экосистеме. В результате, эффективная организация водоподготовки становится важным конкурентным преимуществом и вложением в устойчивое развитие, как для производств, так и для сообщества.
In the awesome design of things you get an A for effort and hard work. Where exactly you lost everybody ended up being on the specifics. You know, people say, details make or break the argument.. And it could not be more true right here. Having said that, let me inform you just what did do the job. The article (parts of it) is actually pretty convincing which is probably the reason why I am taking an effort in order to comment. I do not really make it a regular habit of doing that. Next, even though I can notice a jumps in logic you make, I am not confident of just how you seem to connect the details that help to make your final result. For right now I will, no doubt subscribe to your point but hope in the foreseeable future you link the facts much better.
VISIT TICKETWIPE TO BEAT YOUR SPEEDING TICKETS. DON’T PAY THEM!!!!
Today the Board of Trade Building is closely joined by numerous skyscrapers in the heart of Chicago’s busy Loop commercial neighborhood.
This is a correct blog for anybody who really wants to be made aware of this topic. You understand so much its practically challenging to argue along (not too I actually would want…HaHa). You certainly put the latest spin with a topic thats been discussed for decades. Great stuff, just wonderful!
brand hytrin – where to buy tamsulosin without a prescription buy priligy generic
Well, this Thursday I read through a couple of your posts. I must say this is one of your better ones. .
Welcome to our portal, your top source for all the freshest news and updates on the media landscape in the United Kingdom. Whether you’re interested in TV, FM/AM, print, or internet media, we present comprehensive coverage that keeps you informed about the key developments and shifts. From just-in reports to detailed analyses, our team of veteran journalists and industry analysts work relentlessly to bring you the most reliable and latest news – https://ukeventnews.uk/is-listening-to-music-that-evokes-tears-beneficial/
In addition to to stories, we offer perceptive features and opinion essays that delve into the complexities of the press industry. Our stories cover a variety of topics, including regulatory shifts, media control, and the impact of new innovations. We also underline the milestones and hurdles faced by media professionals, offering a platform for voices from throughout the industry to be recognized and respected.
Stay engaged with the pulse of the UK media scene through our regularly updated content. Whether you’re a media professional, a student, or simply a media enthusiast, our portal is designed to accommodate to your preferences and wants. Become part of our growing community of readers and make sure you’re always in the know about the dynamic and always developing world of media in the United Kingdom.
Hey. Neat post. There’s a problem with the site in chrome, and you might want to check this… The browser is the marketplace leader and a good section of other folks will leave out your wonderful writing due to this problem.
I enjoy your composing design, do carry on creating! I will be back!
El Bitcoin, siendo la primera y más conocida criptomoneda, es a menudo el punto de partida en las discusiones sobre criptoactivos. En diciembre de 2017, el Bitcoin alcanzó lo que muchos consideraban su cima, con un valor cercano a los 20.000 dólares. Las criptomonedas están de moda y ya superan los 100 millones de usuarios a nivel mundial. Las criptomonedas suponen una revolución de magnitud global que cambiará cómo compramos, vendemos y ahorramos, pero también cómo están estructuradas las sociedades a nivel político, económico y social. La historia “muestra que puede haber una volatilidad significativa en torno a estos eventos”, lo que supondría un “desafío” para los inversores a corto plazo, según un informe de la plataforma de activos digitales Bit2Me. Otros aseguran que hay que esperar la reacción del mercado de criptomonedas y de su protagonista principal, el Bitcoin. Mientras que hay un tercer grupo que asegura que un Bitcoin podría llegar a valer 100.000 dólares antes de fin de año.
https://www.chunhyesa.com/bbs/board.php?bo_table=free&wr_id=50330
Los estafadores están usando las mismas tácticas de probada eficacia, solo que ahora están exigiendo pagos en criptomonedas. Las estafas de inversiones son una de las principales maneras que usan los estafadores para engañarlo y convencerlo de que compre criptomonedas y se las envíe a los estafadores. Pero los estafadores también se están haciendo pasar por representantes de negocios, agencias del gobierno, relaciones románticas, entre otras tácticas. “Los aranceles estadounidenses tienden a respaldar al dólar a través del canal de sustitución de importaciones, pero el tamaño del impacto cambiario depende crucialmente de los detalles, dijo el equipo de estrategia cambiaria de Barclays en una nota a clientes la semana pasada. Lo que se puede hacer, para convertir los Tether o Bitcoins en dólar billete, es transferirlos a un monedero de alguna otra plataforma que sí permita ventas contra dólares reales. O bien buscar, por fuera de la plataforma, a alguien interesado en hacer la operación de monedero a monedero sin ningún sitio de por medio.
I was on Twitter looking for Neiko Tools when I found a link to this blog, happy I stopped by – Cheers
Excellent beat ! I would like to apprentice whilst you amend your site, how could i subscribe for a blog website? The account helped me a acceptable deal. I have been a little bit familiar of this your broadcast provided shiny transparent idea.
Great site! I recommend to everyone!https://nearstore.com/collections/cartier
Do you mind generally if I cite a few of your content articles so long as I deliver you acknowledgement as well as sources returning to yuor web blog? My web pages is in the similar specialized niche as your site and my site guests will make use of some of the information and facts your site present at this website. Please let me know if it is okay with you. Take care!
Welcome to our site, your premier source for all the latest news and developments on the media landscape in the United Kingdom. Whether you’re keen in telecasts, broadcast radio, press, or internet media, we present extensive coverage that keeps you updated about the key trends and movements. From latest bulletins to comprehensive analyses, our team of seasoned journalists and industry specialists work ceaselessly to bring you the most reliable and recent details – https://ukeventnews.uk/what-are-the-steps-to-move-music-from-one-iphone/
In addition to stories, we provide thought-provoking features and opinion articles that delve into the details of the media industry. Our articles cover a diverse array of topics, including regulatory shifts, media control, and the impact of new advancements. We also highlight the milestones and challenges faced by media professionals, offering a platform for voices from all over the industry to be listened to and appreciated.
Stay in touch with the pulse of the UK media scene through our frequently updated content. Whether you’re a media professional, a student, or simply a media enthusiast, our site is designed to appeal to your needs and needs. Enter our growing community of readers and guarantee you’re always in the know about the dynamic and constantly changing world of media in the United Kingdom.
What is your most noted accomplishment. They may want good listeners rather than good talkers.
Pretty! This was a really wonderful post. Thank you for your provided information. cool desktop
generic speman – buy cheap finasteride buy cheap generic finasteride
Great site! I recommend to everyone!https://nearstore.com/collections/carolina-herrera