AngularJS – Controller 介紹篇

繼續AngularJS的介紹,接下來我們看看controller的應用,以商品介紹的頁面為例,來看看這些資料要如何呈現在頁面上,想要呈現的資料有產品名稱、價格以及描述。

為了方便文章閱讀,本篇將application翻譯成應用程式;controller翻譯成控制器

AngularJS Part2 Slide1

控制器負責定義函數和值來決定整個應用程式的行為,同樣我們把Javascript和HTML分開來開發,在app.js內定義應用程式名稱和控制器的名稱、函數與值,在這次的案例中也提到利用(function(){})()包裝整個javascript是一種好習慣,有關於函式的基本觀念,大家可以閱讀一下這篇文章,介紹的還蠻詳細的!包裝部分的概念可參考其中介紹的立即函示(IIFE – Immediately Invoked Function Expression)。

AngularJS Part2 Slide2

定義好之後可以開始定義該控制器內的值,其中this.product=gem的意思是指未來在輸出時可以利用product.name去取得Dodecahedron;product.price去取得2.95…等等。

AngularJS Part2 Slide3

接下來就是把這些值顯示在網頁上,首先可以在div標籤內加上ng-controller=”StoreController as store”的屬性,其中ng-controller是去指定StoreController為該div內的控制器名稱;store是別名(類似綽號)未來呼叫store時就是在呼叫StoreController這個控制器。

AngularJS Part2 Slide5

在HTML標籤內開始輸出該控制器內的值,分別是:store.product.name、store.product.price、store.product.description三個項目,而在頁面上就會看到這三個值被顯示出來了。

AngularJS Part2 Slide6

需要注意的是,如果我們把輸出值部分的程式碼放在div外側的話,會沒有辦法順利的顯示值,因為我們的控制器是指定於div標籤內,離開了div標籤就無法取得該控制器了。

AngularJS Part2 Slide7

本篇的教學就到這邊,大家也可以透過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官方教學視訊,另有控制器指令介紹的專頁

You may also like...

11,245 Responses

  1. Maxwell表示:

    Beware Of These “Trends” Concerning Auto Accident Compensation Claim baltimore auto accident attorneys (Maxwell)

  2. капельница от запоя нижний новгород капельница от запоя нижний новгород .

  3. 836614.Xyz表示:

    The Best Advice You Could Receive About Designer
    Handbags For Sale 836614.Xyz

  4. Test: How Much Do You Know About Cheap Single Mattress?
    Single Mattress For Electric Bed

  5. DamianGed表示:

    Fonbet промокод на фрибет 2000 промокод на фрибет
    Fonbet предлагает промокоды, которые предоставляют фрибет на сумму до 2000 рублей. Ввод такого промокода при регистрации или внесении депозита активирует бонусные предложения. Примером такого промокода может быть ‘GIFT200’, который предоставляет бесплатные ставки или увеличение суммы депозита, делая игру на платформе более выгодной и интересной.

  6. вывод из запоя стационар (вывода из запоя в стационаре) вывод из запоя стационар (вывода из запоя в стационаре) .

  7. The Most Worst Nightmare Concerning Tree House Twin Bunk Bed Be Realized tree house loft bed

  8. Kindly fellow spectator,

    I found the perspectives shared in this blog post to be highly insightful
    . The writer’s expertise of the subject matter is indeed commendable.

    If you are yearning for a thrilling and gainful cyber gaming experience , I would sincerely
    encourage you to explore the choices of VIVARO CASINO.

    With its abundant selection of captivating amusements , plentiful promotions , and efficient
    experience , VIVARO CASINO facilitates an matchless amusement
    vibe that accommodates both rookie and adept players
    equally .

    I prompt you to try VIVARO CASINO and unveil the buzz that awaits
    you. I am confident you will view the escapade to be exceptionally enjoyable .

    Sincerest regards

    Feel free to surf to my webpage – online casino high roller bonuses

  9. AngdPaish表示:

    It was that bad.
    Significantly reduced prices mean you can what does cephalexin treat is by using online pharmacies
    You should not use the medicines if:Someone is forcing you to end your pregnancy.

  10. 10 Apps That Can Help You Control Your Railroad Accident Lawyer best injury lawyer
    near me (en.sulseam.com)

  11. 5 Killer Quora Answers To Treadmill At Home Treadmill (http://Www.Bbgolfclub.Co.Kr)

  12. ThomasGed表示:

    Промокод от Фонбет промокод фонбет на сегодня при регистрации
    Фонбет регулярно предлагает промокоды, которые предоставляют различные бонусы и привилегии для пользователей. Промокод ‘GIFT200’ активирует бесплатные ставки и другие награды для новых игроков. Использование промокодов делает игру на платформе более интересной и выгодной, предоставляя пользователям дополнительные возможности для выигрыша.

  13. AnrhHesia表示:

    If you have genital herpes, you can keep breastfeeding as long as the sores are covered.
    Consider first-rate online pharmacies the moment you decide to how much neurontin to get high are standard from these trusted pharmacies
    There are several types of medications used to treat congestive heart failure.

  14. AgfnvHesia表示:

    This accounts for the side effects seen with methotrexate use.
    Real savings made if you buy on this site. Cheap what is keflex good for at cheap prices after comparing offers
    Some hereditary disorders make blood clotting more likely.

  15. Jerealas.Top表示:

    10 Websites To Help You Learn To Be An Expert In Double Glazing Repairs Near Me Jerealas.Top

  16. Absorbing and revealing study of the subject matter.

    Your assessment was complete and well-substantiated, presenting audience with
    a exhaustive knowledge of the key concerns at reach.

    I will be ecstatic to engage complementary on this subject.

    If you approve, I would pleasantly invite you to join me
    on the SBOBET site, where we would sustain our exchange
    in a greater participatory context.

    My web blog :: Gaming platforms

  17. Gerald表示:

    A Provocative Rant About Treadmill Electric Motor electric treadmill uk
    [Gerald]

  18. Warmly fellow observer ,

    I uncovered the thoughts shared in this blog post to be
    extremely insightful . The writer’s capability of the
    theme is indeed commendable.

    If you are desiring a electrifying and fruitful web-based gaming
    expedition , I would gladly convince you to uncover the selections of VIVARO CASINO.

    With its abundant array of exciting recreations, generous
    benefits, and efficient layout, VIVARO CASINO facilitates an matchless recreational experience that
    accommodates both beginner and veteran enthusiasts
    correspondingly .

    I urge you to delve into VIVARO CASINO and expose the thrill that awaits you.
    I am firmly believe you will find the journey to be
    extremely rewarding.

    Heartfelt regards

    Feel free to surf to my homepage :: online casino player behavior analytics

  19. 10 Websites To Help You To Become A Proficient In Locksmith For Auto locksmith Near me automotive

  20. 15 Unquestionably Good Reasons To Be Loving Boot Scooter Boot mobility scooters

  21. вывод из запоя стационар (вывода из запоя в стационаре) вывод из запоя стационар (вывода из запоя в стационаре) .

  22. Superb piece on the rise of internet-based gaming.
    As a person who is enthusiastic about this space, I appreciate the comprehensive analysis you provided.

    If individuals looking searching for a alternative platform to explore, I’ve discovered an online destination called BetCryptoCasino.net.
    It features a vast array of casino titles and
    sports betting options, utilizing cryptocurrency for seamless and secure financial operations.

    You can explore it and assess if it matches your gaming preferences.

    Cheers!

    Stop by my page … crypto casino online

  23. Be grateful for Your Insights!

    I’m Elated you Unearthed the Piece Valuable.

    If you’re Curious about Delving into more Avenues
    in the online Betting Domain, I’d Propose Exploring
    CMD368.

    They Deliver a Broad spectrum of Intriguing Sports
    Alternatives, Interactive experiences, and a Accessible Environment.

    What I Highly Favor about CMD368 is their Dedication to Sensible Punting.
    They have Comprehensive Safeguards and Features to Enable Gamblers Exercise control.

    Whether or not you’re a Proficient Sports fan or Unfamiliar with the Game, I Suspect
    you’d Truly Delight in the Venture.

    Feel free to Register By way of the Channel and Inquire if you have Other Concerns.

    Visit my web-site … cmd368 singapore; chart-studio.plotly.com,

  24. Why You Should Not Think About Improving Your Slot Demo Zeus Vs Hades Rupiah oscarreys.top (maps.google.com.uy)

  25. Salutations, comrade reader. I must extol the author for their
    thoughtful and skillfully-written blog post. The content was both informative and thought-provoking, leaving me with a deeper understanding of
    the matter at hand.

    I would wish to extend an appeal to participate in the eminent PUSSY888 group.
    This place offers a sphere of entertainment and intrigue,
    catering to those who adore the more distinguished things in world.

    I exhort you to explore the diverse possibilities and immerse yourself in the exciting ventures that beckon you.

    Your inclusion would be very cherished, and I await with excitement the opportunity to dialogue with
    you more thoroughly within this illustrious cyber landscape

    My web page :: online casino responsible gaming

  26. Five Window Companies Leeds Lessons From The Professionals upvc window repairs leeds

  27. Wnenonert表示:

    Whether you’re concerned about breast pain or tenderness, it’s important to stay informed on risk factors and warning signs of breast cancer.
    Any consumer can easily nolvadex side effects pct Online pharmaci
    No promo code necessary.

  28. Buzzwords De-Buzzed: 10 Other Methods To Deliver Outdoor Couches For Sale cheap sectionals for sale

發佈留言

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