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,153 Responses

  1. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервис центры бытовой техники москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  2. What Is Skoda Superb Replacement Key? History Of Skoda Superb
    Replacement Key Skoda Octavia 2 Key Programming (https://Posteezy.Com/)

  3. Enthralling and perceptive examination of the subject matter.
    Your assessment was in-depth and well-evidenced, furnishing
    followers with a exhaustive insight of the main topics at
    disposal.

    I could be excited to communicate extra on this matter.

    If you are willing, I would cordially request you to participate in me on the SBOBET website, where we will extend our conversation in a greater engaging environment.

    my site; online casino player behavior

  4. HarryGed表示:

    Qu’est-ce qui donne au joueur la verification dans 1xbet?
    La verification est une procedure obligatoire pour les clients du bookmaker 1xBet Haiti. La procedure prevoit la verification des donnees personnelles du client pour la conformite avec les donnees reelles qui sont presentees sur la carte d’identite.

  5. Foldable Rollator With Seat Tools To Ease Your Daily Lifethe One Foldable Rollator With Seat
    Trick That Everybody Should Learn Foldable rollator with seat

  6. Ten Single Coffee Machines That Really Help You Live Better Single Coffee Machines

  7. электрический карниз для штор цена электрический карниз для штор цена .

  8. 5 Private Psychiatrist Nottingham Leçons
    From The Professionals private psychiatry london

  9. Pragmatic Free Slots 10 Things I’d Loved To
    Know Earlier 프라그마틱 슬롯무료

  10. автоматические карнизы для штор цена автоматические карнизы для штор цена .

  11. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники

  12. The Most Pervasive Issues In Retro Fridge Freezer Frost
    Free durable Side by side Fridge freezer

  13. 3222914.xyz表示:

    17 Signs To Know You Work With Headphones Wireless Beats 3222914.xyz

  14. Undisputed Proof You Need Foldable Travel Wheelchair folding travel
    wheelchair (https://smokesystem7.werite.Net)

  15. 5 Killer Quora Answers On Citroen Ds3 Key Replacement
    Citroen Ds3 Key Replacement

  16. The 10 Most Scariest Things About Patio Sliding Door
    Repair Near Me Patio sliding door repair near me

  17. What Freud Can Teach Us About Freezer Fridge 50 50 Fridge Freezer Built In 50/50

  18. Mary表示:

    The Next Big New Mobility Scooter Industry lightweight
    mobility scooters (Mary)

  19. Could Assessment For Adhd In Adults Be The Key To Achieving 2023?
    Why Are Adhd Assessments So Expensive (Anipi-Italia.Org)

  20. The world of cutthroat gaming has undergone a remarkable metamorphosis
    in recent years, with the rise of esports as
    a global rage . Amidst this rapidly developing landscape, one name
    has emerged as a trendsetter – Spade Gaming.

    Spade Gaming is a influence to be reckoned with, a gaming company that has carved out a unique forte for
    itself by blending cutting-edge advancement , strategic vision ,
    and a relentless commitment to dominance .

    Established with the goal of rethinking the boundaries
    of challenging gaming, Spade Gaming has quickly become a emblem of creativity , driving the field
    forward with its revolutionary approach and steadfast
    dedication.

    At the core of Spade Gaming’s triumph lies its unflagging
    commitment on individual development and collective
    building. The establishment has cultivated an habitat that
    enables and empowers its participants ,
    providing them with the equipment , education ,
    and support they need to realize new pinnacles .

    But Spade Gaming’s influence extends far outside of the
    confines of the game by itself . The entity has also cemented
    itself as a innovator in the domain of material creation, maximizing its vast assortment
    of virtuosic practitioners to develop gripping and spellbinding media that strikes a chord with enthusiasts across the planet .

    On top of that , Spade Gaming’s dedication to social
    duty and community involvement sets it one-of-a-kind
    from its opponents. The conglomerate has tapped into
    its megaphone to champion vital efforts , deploying its
    significance and influence to foster a transformative
    contribution in the domain of esports and
    stretching wider .

    As the professional gaming field prevails to evolve
    , Spade Gaming commands as a glowing model of what can be
    secured when perspective , originality , and a unyielding
    mission of dominance fuse .

    In the epoch to unfold , as the ecosystem of cutthroat
    gaming persists to enthrall devotees and revolutionize the means we involve with amusement , Spade Gaming will assuredly endure at the fore, guiding the initiative and constructing
    a novel chapter in the perpetually morphing world of esports.

    Feel free to visit my page :: online casino mobile optimization

  21. Why All The Fuss About Coffee Machines Espresso?

    Mini Espresso Machine

  22. Repairs To Upvc Windows Tools To Make Your Daily LifeThe One Repairs
    To Upvc Windows Trick Every Person Should Be Able To repairs To upvc Windows

  23. DouglasHoapy表示:

    1xbet промокод на депозит
    For users in Sri Lanka, 1xBet provides specific promo codes tailored to the region. These codes may offer bonuses like free bets, deposit matches, or other rewards, making it an attractive option for bettors in the country.

  24. Ten Reasons To Hate People Who Can’t Be Disproved Pragmatic
    Slots Free Trial 프라그마틱 정품

  25. 10 Things You Learned In Kindergarden That’ll Help You With Replacement Audi Key audi key fob not working

  26. интересные бизнес идеи интересные бизнес идеи .

  27. 20 Things That Only The Most Devoted Nespresso Machine Sale Fans Know
    Nespresso machine black Friday (https://fraser-kemp.technetbloggers.de/)

發佈留言

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