AngularJS – 跟著Google玩網頁!

今天馬老師要與大家分享的是一個前端開發的函式庫AngularJS,前面的文章中都有提到,因為近年來行動裝置的普及讓Javascript大為活躍,不過傳統的Javascript在相容性上、操作上都非常的不方便,所以才有了許許多多Javascript的函式庫與框架的誕生,例如:jQuery、KnockoutJS、GSAP、PaperJS…等,每個Javascript的函式庫和框架的大小、作用和目的都不盡相同,有的是為了特效;有的則是為了方便操作,那今天為何要跟大家分享AngularJS呢?因為…它是名牌!

AngularJS 示意圖

為何說AngularJS是名牌呢?因為目前他是由Google來負責維護。初始版本是在2009年誕生的,比jQuery晚了三年,言下之意就會比jQuery好嗎?當然也不能這麼說,jQuery在目前還是一個非常火燙的前端開發函式庫,應該要說他們兩個在使用的架構和目的上會有所不同,這篇文章也來比較一下同樣的案例,在兩種語法上面撰寫的不同。

AngularJS 官方網頁截圖
AngularJS 官方網頁截圖

不過首先我們要知道基本的AngularJS開發方式,今天的案例我們利用JS Bin的線上開發網頁來說明,大家也可以到這個平台上來試著玩看看!如果需要利用AngularJS開發自己的網頁,也可以到AngularJS的官方網頁把JS下載到資料夾之後引用到網頁裡。

1. 首先點選Add library後選擇AngularJS Stable,這樣該平台就會加入AngularJS的函式庫進入頁面。

AngularJS JS Bin Add Library
AngularJS JS Bin Add Library

2. 在標籤中,加入ng-app的屬性,讓整份文件都可以使用AngularJS。

AngularJS JS Bin 增加 HTML 屬性
AngularJS JS Bin 增加 HTML 屬性

3. 接下來就可以在左手邊body標籤內開始輸入一些程式碼來測試,AngularJS在輸出方面有個基本的結構式「{{ }}」,大家輸入以下的程式碼來測試看看結果:  

<!DOCTYPE html>
<html ng-app>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
	<meta charset="utf-8">
	<title>JS Bin</title>
</head>
<body>
	<p>{{ '馬老師雲端研究室' }}</p>
	<p>35+62={{ 35+62 }}</p>
	<p>NT{{ 62000 | currency }}</p>
</body>
</html>

可以看到輸出的結果應該是:(在JS Bin上面看AngularJS輸出結果

馬老師雲端研究室

35+62=97

NT$62,000.00

同樣的如果我們要利用jQuery來完成這樣的頁面,程式碼就會變成:(在JS Bin上面看jQuery輸出結果

<!DOCTYPE html>
<html>
<head>
	<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
	<meta charset="utf-8">
	<title>JS Bin</title>
</head>
<body>
	<p></p>
	<p></p>
	<p></p>
</body>
</html>
<script>
	$("p:eq(0)").text('馬老師雲端研究室')
	$("p:eq(1)").text('35+62=' + (35 + 62))
	$("p:eq(2)").text('NT' + (numeral(62000).format('$ 0,0.00')))
</script>

請注意,為了要完成第三項貨幣型式的呈現,我們還必須去引用這個網站的jQuery Plugin才有辦法比較輕鬆的實現。從上面的案例可以看的出來jQuery是由HTML DOM來抓到對象,再針對對象做操作,而AngularJS不管顯示的效果為何,就是在需要有程式運算的地方出現,所以AngularJS也被稱為符合MVC結構的Javascript函式庫(MVC是一種寫程式的結構,全名是Model View Controller,大家可以上網Google就可以查到很多與MVC相關的資料),但如果你有進入官網,可以看到官網上他的標題是「AngularJS – Superheroic JavaScript MVW Framework」,翻譯成中文大概是「AngularJS是一個符合MV…Whatever什麼什麼隨便啦!的超級函式庫」,可以看出Google的惡搞功夫。

再來示範第二個案例,本案例利用購物行為來製作相關的頁面讓大家參考,程式碼如下:

<!DOCTYPE html>
<html ng-app>
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
	<meta charset="utf-8">
	<title>JS Bin</title>
</head>
<body ng-init="stock=120;price=325;quantity=1;total=0">
	<p>馬老師雲端研究室 滑鼠墊</p>
	<p>剩餘:<span ng-model="stock">{{ stock-quantity }}</span>個</p>
	<p>單價:<span ng-model="price">{{ price | currency:"NT$":0 }}</span>元</p>
	<p>數量:<input type="number" min="0" max="{{ stock }}" ng-model="quantity"></p>
	<p>總金額:<span ng-model="total">{{ price*quantity | currency:"NT$":0 }}</span></p>
</body>
</html>

輸出結果:(在JS Bin上面看AngularJS輸出結果

AngularJS JS Bin 輸出結果
AngularJS JS Bin 輸出結果

在這個案例裡面有四個項目,分別是商品剩餘數量、單價、數量、總金額,使用者唯一可以改變的只有數量,但頁面中會自動運算剩餘數量和總金額,其中在語法body標籤中,加上了ng-init屬性,代表設定這幾個項目的預設值,stock(剩餘數量)120個、price(單價)325元、quantity(數量)1個,total(總金額)325元。接下來在span內的ng-model就是去綁定該定義項目,{{  }}則是顯示該項目或運算結果,另外貨幣格式的部分,也是用了一些設定讓貨幣在這個案例裡面顯示得更為接近台幣格式,另外還是用HTML5 input標籤的min和max來限制欄位內的值。 而這個案例如果轉換為jQuery的寫法,大概會是下面這樣子:(在JS Bin上面看jQuery輸出結果

<!DOCTYPE html>
<html>
<head>
	<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
	<meta charset="utf-8">
	<title>JS Bin</title>
</head>
<body>
	<p>馬老師雲端研究室 滑鼠墊</p>
	<p>剩餘:<span id="stock"></span>個</p>
	<p>單價:<span id="price"></span>元</p>
	<p>數量:<input type="number" min="0" ng-model="quantity" id="quantity"></p>
	<p>總金額:<span id="total"></span>元</p>
</body>
</html>
<script>
	var stock = 120;
	var price = 325;
	var quantity = 1;
	var total = 325;
	$("#stock").text(stock) $("#price").text('NT' + (numeral(price).format('$ 0,0'))) $("#quantity").val(quantity).attr(
		"max", stock) $("#total").text('NT' + (numeral(total).format('$ 0,0'))) $("#quantity").change(function () {
		quantity = $(this).val() newstock = stock - $(this).val() total = price * $(this).val() $("#stock").text(
			newstock) $("#price").text('NT' + (numeral(price).format('$ 0,0'))) $("#total").text('NT' + (
			numeral(total).format('$ 0,0')))
	})
</script>

後記:以上兩個案例示範的是jQuery和AngularJS在撰寫頁面的不同,不過因為這篇文章原本就是要以AngularJS為主,所以挑的案例當然會是AngularJS比較佔優勢的內容,還是跟我常說的一樣,做不同的東西就要用不同的工具,用錯了工具不是做不到,但可能是會事倍功半的!另外文章中的程式碼,都是嵌入遠端的JS檔,所以也可以把整個程式碼複製到你熟悉的網頁開發軟體內,一樣會看到同樣的結果喔!

You may also like...

4,270 Responses

  1. Oh my goodness! a wonderful write-up dude. Thanks a ton Even so I am experiencing trouble with ur rss . Do not know why Struggling to sign up for it. Perhaps there is any person acquiring identical rss difficulty? Anyone who knows kindly respond. Thnkx

  2. Provadent表示:

    This article is great. I gained a lot from going through it. The information is very enlightening and structured.

  3. Well i’m from Ireland, and throughout Ireland bono and the lads are unquestionably liked and also could certainly not do really much incorrect, we all love them.

  4. This is a really great blog your have here but I had some questions about advertising on your site. So if you could reply to this post with a contact email, that would be great.

  5. Online Casino表示:

    Spot on with this write-up, I truly feel this web site needs a great deal more attention. I’ll probably be back again to read more, thanks for the information!

  6. Terrific article. It’s highly well-written and packed with beneficial information. Many thanks for providing this information.

  7. PRODENTIM表示:

    Terrific entry. It offered tons of valuable details. I am grateful for the work you invested to create this information.

  8. Excellent website. Lots of useful info here. I’m sending it to a few friends ans also sharing in delicious. And obviously, thanks for your effort!

  9. I have to show my appreciation to the writer just for bailing me out of this particular circumstance. Just after exploring throughout the world-wide-web and finding solutions that were not beneficial, I figured my life was over. Living without the approaches to the difficulties you’ve fixed through your good short post is a crucial case, and those that would have badly affected my entire career if I had not come across your site. Your personal knowledge and kindness in touching the whole thing was useful. I don’t know what I would have done if I hadn’t come across such a thing like this. I can also now relish my future. Thanks a lot so much for the impressive and amazing help. I won’t be reluctant to suggest your web page to any person who desires guidance on this matter.

  10. I used to be able to find good information from your content.

  11. sunwin表示:

    Excellent article! We will be linking to this particularly great article on our site. Keep up the great writing.

  12. sunwin表示:

    Good day! I could have sworn I’ve visited this web site before but after browsing through a few of the posts I realized it’s new to me. Anyways, I’m certainly pleased I discovered it and I’ll be book-marking it and checking back often!

  13. my hard drive is getting full already because i always download free online movies on the internet“

  14. 오피表示:

    I’m going to share this on social media.오피

  15. sky88表示:

    Good article! We will be linking to this great post on our site. Keep up the great writing.

  16. of course data entry services are very expensive that is why always make a backup of your files-

  17. AncrPaish表示:

    Healthy Eating Learn about eating well and proper nutrition.
    And convenience are the main reasons for buying 100mg sildenafil safe for ED patients. Visit and learn more.
    Adults may be able to infect others 1 day before getting symptoms and as long as 5 days after getting sick.

  18. Sweet website , super style and design , really clean and utilise pleasant.

  19. Luigielasp表示:


    Идеи вашего дома. Информация о дизайне и архитектуре.

    Syndyk – это место, где каждый день вы можете увидеть много различных дизайнерских решений, деталей для вашей квартиры, проектов домов, лучшая сантехника.

    Если вы дизайнер или архитектор, то мы с радостью разместим ваш проект на Сундуке. На сайте можно и даже нужно обмениваться мнениями и информацией о дизайне и архитектуре.

    Сайт: syndyk.by

  20. This is very useful suggestions. I have to say I really like reading this article alot. It helps me to turn into better grasp about the subject. It is all well and good produced. I will definitely search for this kind of material incredibly intriguing. Hopefully you can present more one day.

  21. ArchieToult表示:


    Всё о строительстве, дизайне и ремонте в своём доме.

    Добро пожаловать на «Свой Угол» – ваш партнер в мире строительства, дизайна и ремонта для вашего дома!
    Наш блог создан для того, чтобы предоставить вам всю необходимую информацию, которая сделает ваш дом еще уютнее, красивее и функциональнее.

    Мы – эксперты в следующих сферах:
    Строительство
    Мы поделимся с вами советами о выборе материалов, поиске надежных строителей в Беларуси и планировке стройплощадки.
    Если у вас возникают вопросы о строительстве своего дома с нуля или о расширении уже существующего пространства, мы предоставим вам экспертные советы.

    Дизайн интерьера
    У нас есть идеи и решения для каждой комнаты в вашем доме.
    Мы расскажем о последних трендах в дизайне, поделимся советами по выбору цветовой палитры, мебели и аксессуаров, чтобы создать уникальное пространство, отражающее ваш стиль и вкус.

    Ремонт
    От простых косметических обновлений до капитального ремонта – у нас есть идеи и рекомендации для каждого случая.
    Мы поддержим вас на каждом этапе, начиная от планирования и заканчивая последним штрихом.

    Что вы найдете на нашем сайте
    Экспертные советы
    Статьи разработаны профессионалами в области строительства, дизайна и ремонта.

    Полезные ресурсы
    Ссылки на проверенные магазины, услуги и материалы, которые помогут вам в ваших проектах.

    Модные тренды
    Мы следим за последними тенденциями и новинками в мире строительства и дизайна.

    «Свой Угол» – ваш проводник в мире уюта и стиля в вашем доме. Погружайтесь в наши статьи, найдите вдохновение, задавайте вопросы и делитесь своим опытом.
    Создайте свой угол вместе с нами!

    Информационный портал «Свой Угол»

  22. I have wanted to write about something like this on my webpage and you gave me an idea. Cheers.

  23. Your blog is one of a kind, i love the way you organize the topics.:’-”‘

  24. Qfunlx表示:

    rumalaya price – buy generic rumalaya for sale amitriptyline online

  25. for yet another great informative article, I’m a loyal reader to this blog and I can’t say how much valuable information I’ve learned from reading your content. I really appreciate all the hard work you put into this great blog.

  26. We still cannot quite think that I could truthfully often be those types of checking important points entirely on your blog post. My children and so i are sincerely thankful for one’s generosity too as for giving me possibility pursue our chosen profession path. Information you information I received with your web-site.

  27. Wtmgonert表示:

    It may seem hopeless at first, but with herbs and nutrients, you are fully armed for relief from body heat, sweating, and panic.
    You can search any drug online when you want to sildenafil 20 mg how many can i take can be a sexual stimulant for women?
    The best advice for the loved ones is to not take it personally, as hard as that may be.

  28. That song sucks i think, my younger brother is listening that, and its so boring song !

  29. It’s difficult to acquire knowledgeable folks for this topic, however, you appear to be what happens you’re talking about! Thanks

  30. Nice post. I understand something much harder on diverse blogs everyday. Most commonly it is stimulating to learn to read content off their writers and employ a little something from their site. I’d opt to use some while using content on my own weblog whether you do not mind. Natually I’ll provide link in your internet blog. Many thanks sharing.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。