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

  1. LarrySwall表示:

    поисковое seo в москве https://seo-5.ru

  2. www.metooo.es表示:

    I came across your blog post to be a thought-provoking and
    wise examination of the recent state of the sector .
    Your investigation of the key dynamics and challenges encountering
    organizations in this sphere was unusually convincing
    .

    As an ardent devotee of this issue , I would be
    honored to extend this discourse more extensively.
    If you are enthusiastic , I would joyfully urge you to discover the thrilling prospects available at
    WM casino [http://www.metooo.es].
    Our platform supplies a advanced and guarded atmosphere
    for collaborating with compatible professionals and
    securing a multitude of knowledge to hone your awareness of
    this ever-changing landscape . I eagerly await the potential of partnering with
    you in the approaching future

  3. электрокарниз для штор купить электрокарниз для штор купить .

  4. koin 6 news表示:

    Your passion for this topic is contagious! After reading your blog post, I can’t wait to learn more.

  5. Remarkable Article Feedback
    Impressive , what a thought-provoking entry! I really enjoyed perusing your
    insights on this subject .
    As a person who has been monitoring your digital platform for a period of time ,
    I need to convey that this is amidst your most
    eloquently crafted and engaging pieces so far .
    The fashion you integrated various perspectives and scientific results was
    really impressive . I encountered myself nodding as I read
    since your points simply appeared to unfold
    incredibly seamlessly .

    My web page: bk8 casino – bk8casinoreview.free.site.pro,

  6. Lraznt表示:

    rumalaya generic – buy amitriptyline 10mg generic order elavil 50mg generic

  7. I have exhaustively delighted in the musings provided in this
    reflective blog entry . The writer has skillfully
    elucidated several fundamental notions that align with me
    profoundly .

    As an devoted advocate of groundbreaking entrepreneurial endeavors , I would
    intend to provide an solicitation to you to discover the outstanding
    chances available at Pragmatic Play.

    This thriving company is at the apex of pioneering leaps, presenting a
    thriving and meaningful domain for devotees who possess
    a dedication for excellence and a ambition
    to advance the frontiers of what is possible .

    I encourage you to reflect on this appeal and delve into the profusion of possibilities that present themselves
    . Please feel free to query if you have any doubts
    or would like to talk about more extensively .

    Kindest regards ,

    Here is my homepage online casino customer lifetime value

  8. 24 Hours To Improving Replacement Car Key Cost car Key replacement cost

  9. Jessewrify表示:

    vibration analysis
    The Cruciality of Resonance Management Tools in Mechanical Systems
    Across production sites, machines and rotational machinery serve as the backbone of operations. However, an of the highly prevalent challenges that could obstruct the operation and lifespan is resonance. Vibrations could lead to an variety of challenges, including reduced precision and productivity leading to greater damage, in the end resulting in pricey interruptions as well as maintenance. This scenario is why vibration regulation tools becomes necessary.

    The Reason Vibration Management proves Critical

    Resonance in equipment can result in various harmful impacts:

    Decreased Functional Efficiency: Excess vibrations might result in misalignments and distortion, lowering overall efficiency of such systems. This could cause delayed output times along with greater energy use.

    Greater Deterioration: Persistent vibrations accelerates the wear and tear of machinery parts, bringing about additional repairs as well as the risk for unexpected issues. This doesn’t merely increases operational costs but also shortens the longevity in the equipment.

    Safety Concerns: Excessive resonance may introduce considerable security risks to both the machinery and the personnel. In, severe cases, it might cause cataclysmic system collapse, threatening workers and causing significant harm across the site.

    Precision and Quality Concerns: In sectors where depend on exact measurements, including production and aviation, oscillations may cause flaws with manufacturing, causing faulty goods and increased waste.

    Economical Options to Vibration Control

    Investing into vibration management systems proves not just a necessity and a wise choice for any industry that uses mechanical systems. We offer advanced vibration control systems work to intended to eliminate vibrations within various machine as well as spinning equipment, ensuring smooth as well as productive processes.

    One thing that sets our apparatus apart remains its reasonable pricing. We know the significance of cost-effectiveness in today’s competitive market, which is why our offerings include premium oscillation control tools at prices that won’t break the bank.

    By selecting these tools, you are not just safeguarding your machinery and boosting its operational effectiveness you’re also investing into the enduring success of your business.

    Conclusion

    Resonance mitigation is a necessary aspect of maintaining the effectiveness, safety, as well as lifetime of your machinery. With these reasonably priced oscillation control systems, you can ensure that your operations operate seamlessly, all manufactured items maintain top quality, and all personnel remain safe. Never allow oscillation jeopardize your business—invest in the proper tools today.

  10. Tanisha表示:

    What’s The Current Job Market For Glass Patio Door Repair Professionals?
    glass patio door repair (Tanisha)

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

  12. You’ll Never Guess This Double Glazing Repairs Milton Keynes’s Tricks double glazing Repairs milton keynes;
    doctortitle16.bravejournal.net,

  13. The Little-Known Benefits To Private Diagnosis For
    ADHD Adhd Diagnosis Cost Uk

  14. Lewisslund表示:

    Please let me know if you’re looking for a author for your site. You have some really good posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d love to write some content for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Many thanks!

    https://uemfm.uem.br/files/pags/pin-up-aposta_3.html

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

  16. LloydWhope表示:

    resume for it engineer resume of engineer

  17. What an illuminating and thought-provoking article ! I must declare , your
    examination of this pivotal topic was genuinely outstanding .

    The scope and subtlety you introduced to the conversation was extraordinary , shedding new light on the
    intricacies at play .
    I came across myself agreeing as I read through
    your masterfully composed assertions . The way you were capable
    to extract the core themes excepting oversimplifying
    was specifically remarkable .
    It’s evident you’ve dedicated a great deal of energy into
    researching this topic .
    This write-up has provided me a great deal to ponder and has prompted me to
    rethink specific elements of my personal viewpoint .

    I am grateful for you taking the energy to share your expertise – write-ups like this are immensely valuable in advancing the more
    expansive discussion .
    I eagerly await skimming more of your material in the months to follow.
    Kindly maintain the superb work !

    my blog post :: situs slot gacor microgaming

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

  19. keys表示:

    Car Keys Programmed Techniques To Simplify Your Daily Life Car Keys Programmed Trick That
    Should Be Used By Everyone Be Able To keys

  20. irobot Store表示:

    Irobot Store Tools To Improve Your Daily Life Irobot Store Trick That
    Should Be Used By Everyone Be Able To irobot Store

  21. EarnestAvada表示:

    I was able to find good advice from your blog posts.
    вавада сейчас

  22. RobertGed表示:

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

  23. The Unspoken Secrets Of Single Bunk Bed With Desk
    single Bunk beds

  24. Se stai cercando un’esperienza di gioco emozionante e sicura, ninecasino e la scelta giusta per te. Con un’interfaccia user-friendly e un login semplice, ninecasino offre un’ampia gamma di giochi che soddisferanno tutti i gusti. Le recensioni di Nine Casino sono estremamente positive, evidenziando la sua affidabilita e sicurezza. Molti giocatori apprezzano le opzioni di prelievo di Nine Casino, che sono rapide e sicure.

    Uno dei punti di forza di ninecasino e il suo generoso bonus di benvenuto, che permette ai nuovi giocatori di iniziare con un vantaggio. Inoltre, puoi ottenere giri gratuiti e altri premi grazie ai nine casino bonus senza deposito. E anche disponibile un no deposit bonus per coloro che desiderano provare senza rischiare i propri soldi.

    Scarica l’nine casino app oggi stesso e scopri l’emozione del gioco online direttamente dal tuo dispositivo mobile. Il download dell’app di Nine Casino e semplice e veloce, permettendoti di giocare ovunque ti trovi. Molti si chiedono, “nine casino e sicuro?” La risposta e si: ninecasino e completamente legale in Italia e garantisce un ambiente di gioco sicuro e regolamentato. Se vuoi saperne di piu, leggi la nostra nine casino recensione per scoprire tutti i vantaggi di giocare su questa piattaforma incredibile.
    recensioni nine casino https://nine-casino-italia.com/ .

  25. 9779342表示:

    10 Graphics Inspirational About Oil Radiator Black 9779342

  26. 11 Methods To Totally Defeat Your Program Car Key fob key programmer
    [https://Scientific-programs.science]

發佈留言

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