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

9,487 Responses

  1. электрические гардины электрические гардины .

  2. Dereketerm表示:

    cheap priligy: priligy maxpharm – cheap priligy

  3. карнизы с электроприводом карнизы с электроприводом .

  4. вызов нарколога на дом круглосуточно http://www.masa.forum24.ru/?1-16-0-00002626-000-0-0-1730730156/ .

  5. автоматический карниз для штор автоматический карниз для штор .

  6. StevenNub表示:

    pharmacy cost of prednisone: ray pharm – prednisone 5 tablets

  7. Dereketerm表示:

    cost of prednisone: prednisone ray pharm – 1250 mg prednisone

  8. Lazrkss表示:

    Покупка диплома о среднем полном образовании: как избежать мошенничества?
    bahchisaray.org.ua/index.php?showtopic=34188

  9. StevenNub表示:

    amoxicillin tablets in india: order amoxicillin uk – amoxicillin cost australia

  10. Cordial greetings , comrade viewer . I stumbled upon your profound
    analysis on the blog submission extremely penetrating.

    Your outlook on the subject matter is rather praiseworthy .

    As you sound to own a passionate dedication in the matter ,
    I intend to give an summons for you to
    discover the sphere of ‘918KISS’.

    The website provides a broad variety of captivating data that accordingly satisfy
    people comprising heterogeneous preferences.

    I think you would stumble upon the fellowship at ‘918KISS’ as being
    both rewarding and academically engaging .

    I advise you to reflect on associating with us and providing your invaluable
    insights to the unceasing deliberations. Looking forward to possibly welcoming
    you on board .

    Also visit my blog – casino [https://fearless-fish-k8zf6s.mystrikingly.com]

  11. BrandenSlomy表示:

    priligy max pharm: Priligy tablets – dapoxetine price

  12. BrandenSlomy表示:

    can i order generic clomid no prescription: clomid rex pharm – can i purchase generic clomid tablets

  13. The world of fierce gaming has undergone a remarkable
    change in recent years, with the rise of esports as a global hype.
    Amidst this rapidly changing landscape, one name has emerged as a pioneer – Spade
    Gaming.

    Spade Gaming is a might to be reckoned with, a gaming conglomerate
    that has carved out a unique realm for itself by blending cutting-edge science
    , strategic outlook , and a persistent commitment to prowess.

    Established with the goal of rethinking the boundaries of
    fierce gaming, Spade Gaming has quickly become a
    symbol of ingenuity , driving the landscape forward with its
    revolutionary approach and steadfast dedication.

    At the center of Spade Gaming’s success lies its resolute focus on contender
    development and squad building. The corporation has cultivated
    an system that bolsters and uplifts its performers
    , providing them with the provisions , coaching , and aid they need to
    achieve new summits .

    But Spade Gaming’s effect extends far past the
    restrictions of the game itself . The organization has
    also established itself as a pacesetter in the area of content
    creation, leveraging its deep pool of masterful specialists to manufacture enthralling
    and mesmerizing media that appeals to supporters
    encompassing the world .

    Additionally , Spade Gaming’s allegiance to civic obligation and collective collaboration defines it unparalleled from its
    rivals . The enterprise has leveraged its platform to rally behind crucial campaigns , deploying its weight
    and prestige to create a consequential change in the domain of esports and encompassing more .

    As the virtual athletics realm persists to develop , Spade Gaming dominates
    as a luminous paragon of that which can be secured when vision ,
    freshness, and a tireless quest of perfection converge .

    In the age to transpire , as the domain
    of intense gaming persists to captivate spectators and
    transform the approach we engage with leisure , Spade Gaming will definitively prevail at the frontier , directing
    the initiative and building a trailblazing era in the
    continuously progressing field of esports.

    Feel free to surf to my web page :: online casino VIP programs

  14. StevenNub表示:

    buy amoxicillin canada: cheap amoxil – buy amoxil

  15. промокод на подключение робокассаа промокод на подключение робокассаа .

  16. Dereketerm表示:

    Priligy tablets: Priligy tablets – priligy max pharm

  17. Most Popular Apps to Make Money in Pakistan, For Extra Income, That You Didn’t Know About, For Quick Earnings, That Are Suitable for Everyone, with a high rating and positive reviews, which few people talk about, Innovative platforms for earning money in Pakistan, Passive income in Pakistan through applications: myth or reality?, to make money without straining, Effective strategies for making money in Pakistan through apps, Updated platforms for making money in Pakistan, How to make money in Pakistan using mobile apps: simple and profitable, which will lead to financial independence, with guaranteed payments, which will help you achieve financial stability, Earnings in Pakistan using mobile apps: reality or fiction?, Interesting apps for earning money in Pakistan: choose the bestbest online earning websites in pakistan how to earn money online in pakistan for students .

  18. Dereketerm表示:

    can i order generic clomid pills: clomid online – can you buy cheap clomid for sale

發佈留言

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