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...

5,478 Responses

  1. Hi, I do believe this is an excellent website. I stumbledupon it 😉 I am going to revisit yet again since i have book marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

  2. Edisonanazy表示:

    viagra originale recensioni: viagra senza prescrizione – viagra cosa serve

  3. Edisonanazy表示:

    viagra generico in farmacia costo: miglior sito dove acquistare viagra – viagra acquisto in contrassegno in italia

  4. Edisonanazy表示:

    top farmacia online: Farmacie on line spedizione gratuita – Farmacia online miglior prezzo

  5. With lower demand for goods and companies, companies begin laying off staff and at the identical time chorus from elevating costs.

  6. Tie the handkerchief with a string or ribbon, so that you have a small packet of herbs.Before every interview, hold this package and visualize your self strolling in the interview room, radiating confidence.

  7. Because the L.U.M.C. Thirteen newspaper clippings regarding the merger of the Evangelical United Brethren, and the Methodist churches.

  8. My husband had mounted pie plates with tape next the door.

  9. たび すき表示:

    Due to this fact, one can call it a materialist-magical concept, during which an individual’s decisions about perception (materialist or magical) will decide how a lot — if in any respect — magic can have an effect on him or her.

  10. California Listing – California regional directory.

  11. The turn to unions also belied the favored image of digital-first media outlets like VICE and Vox: laid-again workplaces staffed by young, underpaid however pleased writers, fueled by tech startups’ do-what-you-love, libertarian ethos, and housed in places of work that look extra like nightclubs than newsrooms.

  12. Depending on your journey plans and quantity of luggage, you may want walking shoes that double as hiking boots or journey walking shoes that double as costume sneakers.

  13. After a short hour, we exited the prepare into the guts of Tokyo to stroll to our apartment, encountering and having to wade by a staggeringly sheer quantity of human beings.

  14. Normanfer表示:

    farmacia en casa online descuento: farmacias online seguras – farmacia online envГ­o gratis

  15. Kindle. This is not a Gothic per se, but it surely has a variety of the weather of murder and despair and cover-up and purity/innocence being touched by the way by sin, and…

  16. Premium Argentina & Brazil tour requires that you’ve enough and legitimate travel insurance coverage covering medical and private accidents, together with repatriation costs and emergency evacuation.

  17. At this point no one might work out why, but the lady requested that an’ ambulance come get her an’ also asked that her truck be towed to town.

  18. In an early Italian model of the Bible, the “gentle” on Moses’ head was mistranslated as “horn.” Because of this, folks in Michelangelo’s time believed that Moses had horns and symbolized energy, majesty, and power.

  19. Normanfer表示:

    farmacias online seguras: farmacia online barata – farmacias online seguras

  20. Normanfer表示:

    farmacia barata: farmacias online seguras – farmacia online madrid

  21. if you want to hire some good wedding singers, always look for a singer with a background in classical music*

  22. Praegn表示:

    cyproheptadine cheap – order tizanidine 2mg generic zanaflex cost

  23. Normanfer表示:

    farmacia en casa online descuento: tadalafilo – farmacias online seguras

  24. AoolPaish表示:

    The health care team can suggest ways to relieve these problems.
    Who would mind buying online to get a good price of tinidazole online pharmacy from responsible pharmacies online if you desire competitive
    Trichotillomania is often associated with stress, but sometimes occurs while the person is relaxed as well.

  25. AmddPaish表示:

    The procedure iteslf only takes about 8-10 minutes.
    Are there harmful side effects if I take pharmacy viagra france being it is discounted and it treats your medical condition
    That took all of 12yrs, intersticial cystitus, a chronic inflammation of the bladder, no bacteria seen in samples, but scope shows blood and scarring on bladder lining, no known cause, mabye auto immune, allergy, so anti inlfammatories, histamine receptors, nerve end calmers, ove a few year symptoms improved re pain, frequency, generaly health.

  26. Normanfer表示:

    farmacias online baratas: comprar cialis online sin receta – farmacia online espaГ±a envГ­o internacional

  27. Normanfer表示:

    farmacia online espaГ±a envГ­o internacional: farmacia 24 horas – farmacia online madrid

  28. AengHesia表示:

    Doctors look for these lumps during wellness checks in elderly men as well as those with a family history of testicular cancer.
    Checking the price of best online pharmacy to buy xanax pills when you buy through this site
    Search by StateTo learn about heart conditions and stroke, browse any of the topics below.

  29. Normanfer表示:

    farmacia online barcelona: Tadalafilo precio – farmacia en casa online descuento

  30. Normanfer表示:

    farmacia barata: farmacia online envio gratis valencia – farmacia online madrid

發佈留言

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