學習《Angular高級編程》理解以下css
建立以下界面,有導航欄,一個Watchlists面板,面板上有個加號button,一句說明「」Use+to create a list「」html
點擊 + 會彈出以下窗口web
輸入一個name (好比:醫療)一個description(醫療股票監視), Create按鈕就會高亮,點擊create後,就會顯示以下樣式編程
固然是到app/view/目錄下建立Html文件啦,由於這兩個頁面的形式 在後面的設計中會常常 重複 ,因此將他們做爲模板單獨存放,就放在app/view/templates中,一個叫bootstrap
watchlist-panel.html,一個叫addlist-modal.html 做者起的名字都很形象對吧。app
先看第一個頁面的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。好吧。post
<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)">× </button> </a> </div> </div> </div>
AngularJS把不是以ng開頭的都 看作是用戶自定義的directive(好吧,我老是想說是function),須要用它的一條指令生成js文件。學習
yo angular:directive stk-Watchlist-Panelthis
╭(╯^╰)╮ 執行後生成了兩份,具體我如今也不知道爲何,之後理解了再說。anyway,它是在directives目錄生成了stk-watchlist-panel.js
打開看看
'use strict'; /** * @ngdoc directive * @name stockDogApp.directive:stkWatchlistPanel * @description * # stkWatchlistPanel */ angular.module('stockDogApp') .directive('stkWatchlistPanel', function () { return { template: '<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)template:'<div></div>' 哦意思是要返回html內容
2) restrict:'E' 說是 這個有兩個意思,一個是讓這個stkWatchlistPanel做爲一個Element存在,另外一個意思是限制了它的做用範圍,只能在這個上下文中有用,在別的地方就沒用了。
3)link:裏面就是要寫屬性和方法了,怎麼感受像構造函數,
link: function postLink(scope, element, attrs) { element.text('this is the stkWatchlistPanel directive'); }
也就是在這個postLink的函數裏面要寫咱們自定義的指令。
下面是自定義的指令,本身以爲應該就是 先定義一個默認的空的構造函數,也就是AngularJS所說的做用域 scope,而後給這個構造函數,也就是scope建立屬性和方法。仍是看圖說話吧