1. 程式人生 > >AngularJS學習 之 UI以及邏輯生成

AngularJS學習 之 UI以及邏輯生成

為什麽 內置 下界 ext boot bootstrap 目錄 方法 this

學習《Angular高級編程》理解如下

要求:

創建如下界面,有導航欄,一個Watchlists面板,面板上有個加號button,一句說明“”Use+to create a list“”

技術分享

點擊 + 會彈出如下窗口

技術分享

輸入一個name (比如:醫療)一個description(醫療股票監視), Create按鈕就會高亮,點擊create後,就會顯示如下樣式

技術分享

實現

1.UI 也就是html以及css的實現

當然是到app/view/目錄下創建Html文件啦,因為這兩個頁面的形式 在後面的設計中會經常 重復 ,所以將他們作為模板單獨存放,就放在app/view/templates中,一個叫

watchlist-panel.html,一個叫addlist-modal.html 作者起的名字都很形象對吧。

先看第一個頁面的Html:裏面的樣式明顯調用了bootstrap的各種class;裏面的陌生面孔就是ng-click和ng-repeat,這兩個就是AngularJS的東西,現在看

ng-click="showModal()"就是說當用戶點擊button的時候要執行showModal()這個方法,跟onclick="showModal()"是不是一個模子出來的呢,O(∩_∩)O哈哈哈~ 恩,沒什麽難的,ng-repeat在這先不解釋;那麽showModal()這個function在哪裏呢?我們平時的web開發像這個function都是放在xxx.js文件裏,然後都統一放到scripts文件夾裏。AngularJS就換了個新名詞叫 directive中文翻譯說叫指令,目錄就在app/scripts/directives。好吧。

<div class="panel panel-info">
  <div class="panel-heading">
    <span class="glyphicon glyphicon-eye-open"></span>
    Watchlists
    <!-- Invoke showModal() handler on click -->
    <button type="button"
      class="btn btn-success btn-xs pull-right"
      ng-click
="showModal()"> <span class="glyphicon glyphicon-plus"></span> </button> </div> <div class="panel-body"> <!-- Show help text if no watchlists exist --> <div ng-if="!watchlists.length" class="text-center"> Use <span class="glyphicon glyphicon-plus"></span> to create a list </div> <div class="list-group"> <!-- Repeat over each list in watchlists and create link --> <a class="list-group-item" ng-class="{ active: currentList == list.id }" ng-repeat="list in watchlists track by $index" ng-click="gotoList(list.id)"> {{list.name}} <!-- Delete this list by invoking deleteList() handler --> <button type="button" class="close" ng-click="deleteList(list)">&times; </button> </a> </div> </div> </div>

AngularJS把不是以ng開頭的都 看做是用戶自定義的directive(好吧,我總是想說是function),需要用它的一條指令生成js文件。

yo angular:directive stk-Watchlist-Panel

╭(╯^╰)╮ 執行後生成了兩份,具體我現在也不知道為什麽,以後理解了再說。anyway,它是在directives目錄生成了stk-watchlist-panel.js

技術分享

打開看看

‘use strict‘;

/**
 * @ngdoc directive
 * @name stockDogApp.directive:stkWatchlistPanel
 * @description
 * # stkWatchlistPanel
 */
angular.module(‘stockDogApp‘)
  .directive(‘stkWatchlistPanel‘, function () {
    return {
      templateUrl: ‘<div></div>‘,
      restrict: ‘E‘,
      link: function postLink(scope, element, attrs) {
        element.text(‘this is the stkWatchlistPanel directive‘);
      }
    };
  });

哦,書上又是註冊又是依賴的,看的稀裏糊塗。還是自己理解的簡單。開始我們不是創建了StockDog這個項目嘛,AngularJS就給它分配了一個什麽module名字,叫stockDogApp,然後調用自己內置的 .directive()這個方法,這個方法作用就是 返回 用戶 自定義的那些 directives,也叫指令(還是想說是function)。看這裏傳給.directive()的參數就是剛才我們用yo angular:directive指令創建的,只不過去掉了連接符號,O(∩_∩)O哈哈~

看return了些什麽

1)templateUrl:‘<div></div>‘ 哦意思是要返回html內容,那我們就把"app\views\templates\watchlist-panel.html" 給它

2) restrict:‘E‘ 說是 這個有兩個意思,一個是讓這個stkWatchlistPanel作為一個Element存在,另一個意思是限制了它的作用範圍,只能在這個上下文中有用,在別的地方就沒用了。

3)link:裏面就是要寫屬性和方法了,怎麽感覺像構造函數,

今天學到 寫到這 ,明天繼續。。。。

AngularJS學習 之 UI以及邏輯生成