AngularJs是一款來自Google的前端JS框架,該框架已經被應用到Google的多款產品中。這款框架最核心的特性有:MVC,模塊化,自動化雙向數據綁定,語義化標籤,依賴注入,等等。AngularJS 不只僅是一個類庫,而是提供了一個完整的框架。它避免了和多個類庫交互,須要熟悉多套接口的繁瑣工做。它由Google Chrome的開發人員設計,引領着下一代Web應用開發。從如今開始本人逐漸開始從瞭解而且計劃深入的理解學習angularJs,而且把學習心得一點點的積累下來。css
**1,如何自定義標籤**
index.htmlhtml
<html ng-app='app'> <body> <mike></mike> </body> <script src="js/angular.min.js"></script> <script src="mike.js"></script> </html>
爲了讓瀏覽器可以認識這mike個標籤,咱們須要使用Angular來定義一個mike指令前端
(本質上說就是本身來把<mike>這種玩意兒替換成瀏覽器能識別的那些標準HTML標籤)。 mike.js
var APP = angular.module('app', []); APP.directive('mike',function() { return { restrict:'E', template:'<div>Hi angularjs</div>', replace:true }; });
若是路徑沒問題的話,用瀏覽器打開index.html就能夠看到 Hi angularjs. 能夠看到<mike>這個標籤已經被<div>Hi angularjs</div>
這個標籤替換掉了,這也是以上mike.js代碼裏面replace:true
這行配置的做用使其發生了替換,代碼裏面的template配置就是咱們須要的div標籤或者是內容,至於指令restrict:'E'這個配置項的含義,詳情請看下面:angularjs
E:元素 element <mike></mike> 經常使用
A:屬性 attribute <span mike=""></span> 默認web
C:樣式 class <span class="mike"></span> 不經常使用
M:註釋 comment <!----> 不經常使用正則表達式
下面是分別演示的代碼:
dir.htmlexpress
<!doctype html> <html ng-app="app"> <head> <meta charset="utf-8"/> </head> <body> <mike></mike> <div mike></div> <div class="mike"></div> <!-- directive:mike --> <div></div> </body> <script src="js/angular.js"></script> <script src="js/dir.js"></script> </html>
dir.jsbootstrap
var APP = angular.module('app', []); APP.directive('mike', function() { return { restrict: 'AEMC', template: '<div>Hi angularjs</div>', replace: true }; })
上面的demo出來的就是頁面上顯示4個不一樣的 Hi angularjsapi
templateUrl能夠來替代template,目的是爲了可以讓顯示的內容是來自一個Url而不是像上面同樣,這樣顯示的內容很是的有限,並且會使得字符串累加,頁面至關的繁瑣.從而能夠把模板寫到一個獨立的HTML文件中。 數組
2,如何處理標籤中的子標籤
指令的做用是把咱們自定義的語義化標籤替換成瀏覽器可以認識的HTML標籤。那好,若是咱們自定義的標籤內部出現了子標籤,應該如何去處理呢?很顯然,transclude就是用來處理這種狀況的。
transclude.html
<html ng-app='app'> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /></head> <body> <mike> <br/> <span>the first mike</span><br/> <span>the second mike</span> <span>the third mike</span> <p>p 標籤顯示,這個標籤訂義在在span裏面</p> <a>a標籤是定義在p標籤內部,一樣能夠經過ng-transclude顯示</a> <h>h標籤自定義在a標籤內部,一樣能夠顯示在頁面上面</h> </mike> <hr> <mike> </mike> </body> <script src="js/angular.js"></script> <script src="js/transclude.js"></script></html>
transclude.js
var APP = angular.module('app', []); APP.directive('mike',function() { return { restrict: 'E', template: '<div>Hi angularjs <span ng-transclude> <p ng-transclude> <a ng-transclude> <h ng-transclude></h> </a></p></span></div>', //自定義的標籤內部出現了子標籤div裏面有個span,能夠用ng-transclude解決這個問題. transclude: true }; });
transclude的做用能夠簡化地理解成:把<mike>標籤替換成咱們所編寫的HTML模板可是<mike>標籤內部的內容Hi angularjs保持不變。指令有時候會嵌套,因此加上transclude指令能夠保證每個指令的內容不會被替換掉。
3,怎樣使用templateUrl加載html模板
templateUrl.html
<!doctype html> <html ng-app="app"> <head> <meta charset="utf-8"/> </head> <body> <mike></mike> </body> <script src="js/angular.js"></script> <script src="js/templateUrl.js"></script> </html>
templateUrl.js
var APP = angular.module('app', []); APP.directive('mike', function() { return { restrict: 'AEMC', templateUrl: 'hello.html' }; })
hello.html
<html> <head> <meta charset=utf-8/> </head> <body><h1>The content from hello.html</h1></body> </html>
頁面上顯示:The content from hello.html
4,怎樣緩存模板,使其可讓其餘指令使用
$templateCache.put和get分別能夠將模板保存和取出
templateCache.html
<!doctype html> <html ng-app="app"> <head> <meta charset="utf-8"/> </head> <body> <mike></mike> </body> <script src="js/angular.js"></script> <script src="js/templateCache.js"></script> </html>
templateCache.js
var APP = angular.module('app', []); //注射器加載完全部的模塊時,run方法只執行一次 APP.run(function($templateCache){ $templateCache.put("hello1.html","<div>Hi Angularjs</div>") //angular 內置的templateCache將hello1.html模板緩存起來,可讓多個指令使用它 }) APP.directive('mike', function($templateCache) { return { restrict: 'AEMC', template: $templateCache.get("hello1.html"), replace:true } })
hello1.js
<!doctype html> <html> <head> <meta charset="utf-8"/> <style> .id{ width:100px; height:100px; background:red; } </style> </head> <body> <div class="id">This is the content from hello1.html</div> </body> </html>
5,指令執行過程
compile和link
compile函數用來對模板自身進行轉換,而link函數負責在模型和視圖之間進行動態關聯;
做用域在連接階段纔會被綁定到編譯以後的link函數上面;
compile函數僅僅在編譯階段運行一次,而對於指令的每個實例,link函數都會執行一次;
compile能夠返回preLink和postLink函數,而link函數只會返回postLink函數;
若是須要修改DOM結構,應該在postLink中來作這件事情,若是在preLink中作這件事情會致使錯誤;
大多數的時候咱們只要編寫link函數就能夠;
link指令,link函數負責在模型和視圖之間進行動態關聯,下面的demo模擬鼠標滑動,angular加載後臺數據
load.html
<html ng-app='app'> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <div ng-controller="ctrl"> <load>滑動鼠標,加載數據</load> </div> </body> <script src="js/angular.js"></script> <script src="js/load.js"></script> </html>
load.js
var APP = angular.module('app', []); APP.controller('ctrl',['$scope',function($scope){ $scope.loading = function(){ console.log("loading data,please wait...") } }]) APP.directive('load', function() { return { restrict: 'AE', //link函數通常有總共有4個參數 link:function(scope,element,attr){//link函數監聽事件,鼠標滑動 element.bind("mouseenter",function(){//給元素綁定事件,當鼠標進入的時候,加載數據loading data,在控制檯打印console.log("loading data,please wait...") scope.loading()//指令調用方法,加載數據 }) } } }) 也可使用$apply調用到上面的loading方法: var APP = angular.module('app', []); APP.controller('ctrl',['$scope',function($scope){ $scope.loading = function(){ console.log("loading data,please wait...") } }]) APP.directive('load', function() { return { restrict: 'AE', //link函數通常有總共有4個參數 link:function(scope,element,attr){//link函數監聽事件,鼠標滑動 element.bind("mouseenter",function(){//給元素綁定事件,當鼠標進入的時候,加載數據loading data,在控制檯打印console.log("loading data,please wait...") //scope.loading()//指令調用方法,加載數據 scope.$apply("loading()") }) } } })
頁面顯示如圖所示:
若是有多個controller調用多個方法的時候,這個時候就必須在指令中定義屬性了,注意link函數中,屬性的定義必定是小寫的,若是是大寫的字母或是單詞會報錯(loa):
load.html
<html ng-app='app'> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <div ng-controller="ctrl1"> <load Load="loading1()">滑動鼠標,加載數據1111111</load> </div> <div ng-controller="ctrl2"> <load Load="loading2()">滑動鼠標,加載數據2222222</load> </div> </body> <script src="js/angular.js"></script> <script src="js/load.js"></script> </html>
load.js
var APP = angular.module('app', []); APP.controller('ctrl1',['$scope',function($scope){ $scope.loading1 = function(){ console.log("loading1 data,please wait...11111111111111111111111") } }]) APP.controller('ctrl2',['$scope',function($scope){ $scope.loading2 = function(){ console.log("loading2 data,please wait...222222222222222222222222") } }]) APP.directive('load', function() { return { restrict: 'AE', //link函數通常有總共有4個參數 link:function(scope,element,attrs){//link函數監聽事件,鼠標滑動 element.bind("mouseenter",function(event){//給元素綁定事件,當鼠標進入的時候,加載數據loading data,在控制檯打印console.log("loading data,please wait...") scope.$apply(attrs.loa) }) } } })
6,怎樣實現獨立的scope,使得指令綁定互不影響
通常實現雙向數據綁定的時候,因爲scope沒有獨立就會出現下面的狀況:
scope.html <html ng-app="app"> <head> <meta charset="utf-8"> </head> <body> <mike></mike> <mike></mike> <mike></mike> <mike></mike> </body> <script src="js/angular.js"></script> <script src="js/scope.js"></script> </html>
scope.js var APP = angular.module('app', []); APP.directive('mike',function() { return { restrict:'AE', template:'<div><input type="text" ng-model="username"/>{{username}}</div>', replace:true }; });
頁面顯示以下:
爲了實現獨立的scope,咱們須要在scope.js裏面加上scope:{}
,以實現獨立綁定,使得雙向數據綁定時互補影響
var APP = angular.module('app', []); APP.directive('mike',function() { return { restrict:'AE', scope:{},//在這個地方加一個獨立的scope,能夠實現獨立綁定,使得雙向數據綁定時互補影響 template:'<div><input type="text" ng-model="username"/>{{username}}</div>', replace:true }; });
頁面顯示以下:
scope綁定策略
@ 把當前屬性做爲字符串傳遞,還能夠綁定來自外層scope的值,在屬性值中插入{{}}便可
= 與父scope中的屬性進行雙向綁定
& 傳遞一個來自父scope的函數,稍後調用.
@:
scope.html <html ng-app="app"> <head> <meta charset="utf-8"> </head> <body> <div ng-controller="ctrl"> <mike phone="{{msg}}"></mike> </div> </body> <script src="js/angular.js"></script> <script src="js/scope1.js"></script> </html>
scope.js var APP = angular.module('app', []); APP.controller('ctrl',['$scope',function($scope){ $scope.msg = "apple is now very famous for its good looking"; }]) APP.directive("mike",function() { return { restrict:'AE', scope:{ phone:'@'//這裏加上一個@,angularjs自動幫助綁定。 }, template:'<div><h1 style="background:yellow;">{{phone}}</h1></div>' }; });
=:
scope.html <html ng-app="app"> <head> <meta charset="utf-8"> </head> <body> <div ng-controller="ctrl"> <h2>ctrl</h2> <input type="text" ng-model="msg"/><br/> <h2>directive</h2> <mike phone='msg'></mike> </div> </body> <script src="js/angular.js"></script> <script src="js/scope1.js"></script> </html>
var APP = angular.module('app', []); APP.controller('ctrl',['$scope',function($scope){ $scope.msg = "apple"; }]) APP.directive('mike',function() { return { restrict:'AE', scope:{ phone:'='//這裏改爲=,能夠雙向數據綁定,能夠將phone的內容自動綁定到scope上面的msg上面。 }, template:'<input type="text" ng-model="phone"/>' } });
頁面顯示以下圖所示:
&:
scope.html <html ng-app="app"> <head> <meta charset="utf-8"> <link href=""> </head> <body> <div ng-controller="ctrl"> <mike say="saySomething(name)"></mike> </div> </body> <script src="js/angular.js"></script> <script src="js/scope1.js"></script> </html>
scope.js var APP = angular.module('app', []); APP.controller('ctrl',['$scope',function($scope){ $scope.saySomething = function (name){ alert("Hi, "+name); } }]) APP.directive('mike',function() {//定義mike指令 return { restrict:'AE', scope:{ say:'&'//這裏改爲&,say自動綁定 }, template:'<input type="text" ng-model="userName"/><br/>'+'<button style="width:40px;height:20px;background:gray;" ng-click="say({name:userName})">Say</button>'//button調用函數 } });
頁面顯示效果,以下圖所示:
7,form表單驗證
ng-submit:用來提交動做的處理,在controller裏面定義了函數來處理提交後的驗證動做。dditionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes.請參考ngSubmit
ng-class:The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.通常裏面是一個表達式,請參考ngClass
$pristine:是一個boolean值,若是爲true,說明user沒有和form進行交互,也就是說form沒有被修改,參考:$pristine
完整登陸代碼:
<!doctype html> <head> <meta charset="utf-8"/> <link rel="stylesheet" href="css/bootstrap.css"/>//引入bootstrap.css樣式文件 </head> <body> <div class="panel panel-primary" style="width:700px;margin:90px auto;" ng-controller="ProListCtrl">//在controller.js裏面定義一個控制器ProListCtrl,方便angularjs管理界定範圍 <div class="panel-body"> <div class="row"> <div class="col-md-12"> <h2 class="text-center">管理員登陸系統</h2> </div> </div> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" name="loginForm" role="form" ng-submit="submitForm(loginForm.$valid)" novalidate>//submitForm是在controller裏面定義的一個函數,用來驗證loginForm提交的。 <div class="form-group" ng-class="{'has-error':loginForm.emailName.$invalid && !loginForm.emailName.$pristine}">//$pristine是一個boolean,提示form中的屬性emailName是否被用戶修改,True if user has not interacted with the form yet.這裏的意思就是說 //emailForm被用戶修改且email不是合法的就提示報錯。 <!--ng-class="{'has-error':loginForm.emailName.$invalid && !loginForm.emailName.$pristine&&submitted}"確保數據錯誤只有在提交的時候纔會顯示--> <label class="col-md-2 control-label"> 用戶名: </label> <div class="col-md-10"> <input type="email" name="emailName" class="form-control" placeholder="請輸入註冊郵箱" ng-model="user.email" required>//user是在controller中定義的一個函數,定於email,pwd,和autoLogin的值 <p ng-show="loginForm.emailName.$invalid && !loginForm.emailName.$pristine" class="alert alert-danger">您輸入的郵箱地址不符合要求,請從新輸入您的登陸郵箱。</p>//class="alert alert-danger"是boostrap裏面的一個樣式,提示危險信息。 </div> </div> <div class="form-group" ng-class="{'has-error':loginForm.pwdName.$invalid && !loginForm.pwdName.$pristine}"> <label class="col-md-2 control-label"> 密碼: </label> <div class="col-md-10"> <input type="password" name="pwdName" class="form-control" placeholder="請輸入登陸密碼" ng-model="user.pwd" ng-minlength="6" ng-maxlength="10">//ng-minlength和maxlength是定義密碼的最大和最小長度 <!--<p ng-show="loginForm.pwdName.$invalid && !loginForm.pwdName.$pristine" class="help-block">密碼不符合要求,且</p>--> <p ng-show="loginForm.pwdName.$error.minlength" class="alert alert-danger">密碼長度不夠,請從新輸入您的登陸密碼。</p>//ng-show 若是密碼輸入不符合要求報錯. <p ng-show="loginForm.pwdName.$error.maxlength" class="alert alert-danger">密碼太長,請從新輸入您的登陸密碼。</p> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.autoLogin"> Auto Login </label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <!--<a class="btn btn-success btn-lg" ng-disabled="loginForm.$invalid">登陸</a>--> <button class="btn btn-success btn-lg" type="submit">登陸</button> <button class="btn btn-default btn-lg" data-toggle="modal" data-target="#mymodal-data" type="button">註冊</button> <!-- 模態彈出窗內容 -->//註冊彈出的框的內容也是bootstrap提供的 <div class="modal" id="mymodal-data" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">用戶註冊:</h4> </div> <form ui-sref="prolist({proType:0})" class="form-group"> <div class="modal-body"> <!--<p class="alert alert-success">註冊啓動成功!</p>--> <div class="form-group"> <label class="col-md-2 control-label"> 用戶名: </label> <div class="col-md-10"> <input type="text" class="form-control" placeholder="請輸入您的註冊郵箱。"> </div> <br/> </div> <div class="form-group"> <label class="col-md-2 control-label"> 密碼: </label> <div class="col-md-10"> <input type="text" class="form-control" placeholder="請輸入您的註冊密碼。"> </div> <br/> </div> <div class="form-group"> <label class="col-md-2 control-label"> 電話: </label> <div class="col-md-10"> <input type="text" class="form-control" placeholder="請輸入您的註冊電話。"> </div> <br/> </div> <input type="submit" value="提交"> </div> </form> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary">保存</button> </div> </div> </div> </div> <!-- <button class="btn btn-default btn-lg" ng-click="setFormData()">註冊</button>--> <button class="btn btn-success btn-lg" ng-click="reset()">清空</button>//reset()是controller裏面定義的一個函數,用來清空form表單 <button class="btn btn-success btn-lg" ng-click="recover()">恢復</button>//recover是controller裏面定義的一個函數,用來填充註冊的內容 </div> </div> </form> </div> </div> </div> </div> </body> </html>
頁面效果演示:
-郵件地址不符合要求
-密碼輸入不符合要求
-註冊用戶框
-登陸成功提示框
8,如何自定義指令mikeaction
需求:我想自定義一個指令mikeaction,能夠實現text的show和hide
mike.html <html ng-app="app"> <head> <meta charset="utf-8"/> </head> <body> <div ng-controller='ctrl'> <mike mikeaction='title'><!--mikeaction:就是利用angular的等值綁定的策略--> {{text}} </mike> </div> </body> <script src="js/angular.js"></script> <script src="js/expend.js"></script> </html>
mike.js var APP=angular.module('app', []); APP.directive('mike', function() { return { restrict : 'EA', replace : true, transclude : true, scope : { title : '=mikeaction'//這裏是固定寫法,實現等值綁定 }, template : '<div>' + '<div class="title" ng-click="click()">{{title}}</div>' + '<div class="body" ng-show="showoff" ng-transclude></div>' + '</div>', link : function(scope, element, attrs) { scope.showMe = false; scope.click = function() {//click內部方法,內部才能調到 scope.showoff = !scope.showoff;//點擊事件,實現收縮 } } } }); APP.controller('ctrl',function($scope) { $scope.title = 'my name is mike,and I can show and hide'; $scope.text = 'Hi,I can show,can you see me'; });
頁面顯示結果:
點擊頁面前
點擊頁面後
9,指令嵌套
需求:我想利用嵌套指令實現點擊按鈕列表,實現show和hide
mike.html <html ng-app="app"> <head> <meta charset="utf-8"/> <style> .m1 { border: 1px solid red; width: 250px; } .m1>.title { background-color: blue; color: white; padding: .1em .3em; cursor: pointer; } .m1>.body { padding: .1em .3em; } </style> </head> <body> <div ng-controller='sctrl'> <!--這是一個嵌套標籤--> <mk> <mike class="m1" ng-repeat="mike in mikes" mikeaction="mike.title"><!--mikeaction:就是利用angular的等值綁定的策略定義的指令,根據mikes遍歷選好的結果來肯定要顯示多少個mike--> {{mike.text}} </mike> </mk> </div> </body> <script src="js/angular.js"></script> <script src="js/expend.js"></script> </html>
mike.js var APP=angular.module('app', []); APP.directive('mk', function() {//定義mk指令 return { restrict : 'EA', replace : true, transclude : true, template : '<div ng-transclude></div>', controller : function() { var mikes = [];//定義數組 this.open = function(selected_m) {//對選中項進行angular操做,方便與裏面的指令進行交互 angular.forEach(mikes, function(mike) {//angular遍歷 if (selected_m!= mike) { mike.showoff = false;//不顯示 } }); } this.add = function(mike) { mikes.push(mike); } } } }); APP.directive('mike', function() {//定義mike指令 return { restrict : 'EA', replace : true, transclude : true, require : '^?mk',//require表示mike依賴外面的mk scope : { title : '=mikeaction'//等值綁定mikeaction指令 }, template : '<div>' + '<div class="title" ng-click="click()">{{title}}</div>' + '<div class="body" ng-show="showoff" ng-transclude></div>' + '</div>', link : function(scope, element, attrs, ctrl) {//ctrl是link的第四個參數,能夠自定義,這個ctrl能夠根據外層的指令mk進行交互 scope.showoff = false; ctrl.add(scope);//調用外層mkadd指令的函數方法 scope.click = function click() { scope.showoff = !scope.showoff; ctrl.open(scope);//調用外層mk指令open方法 } } } }); APP.controller("sctrl",function($scope) { $scope.mikes = [{ title : 'what is your name?', text : 'My name is mike,and I like learning AngularJs' }, { title : 'Click this and you will find something interesting', text : 'Interesting one,and Interesting two,what is the interesting three' }, { title : 'Last but not least,Do not forget to learn something new everyday,I hope we can grow more rapidly', text :'I like learning something new' }]; });
頁面結果顯示:
頁面one
頁面two
頁面three
10,利用angular ui封裝的指令實現show和hide
引入控件ui-bootstrap-tpls, 和bootstrap樣式文件
accordion.html <!doctype html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset="utf-8"> <link rel="stylesheet" href="framework/bootstrap-3.0.0/css/bootstrap.css"> <script src="framework/angular-1.3.0.14/angular.js"></script> <script src="framework/ui-bootstrap-tpls-0.11.0.js"></script> <script src="Accordion.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div ng-controller="ctrl"> <p> <button class="btn btn-default btn-md" ng-click="status.open = !status.open">點擊打開娛樂</button><!--status.open是angular ui包裝好的用法--> <button class="btn btn-default btn-md" ng-click="status.isDisabled = !status.isDisabled">點擊控制獲取權限(你叫什麼名字)</button><!--在js中定義status的狀態,status的狀態也能夠本身定義--> </p> <label class="checkbox"> <input type="checkbox" ng-model="oneAtATime">每次只能打開一個 </label> <accordion close-others="oneAtATime"> <accordion-group heading="你叫什麼名字?" is-disabled="status.isDisabled"><!--頁面默認顯示關閉的--> 我叫 mike. </accordion-group> <accordion-group heading="{{group.title}}" ng-repeat="group in groups"><!--從js文件中獲取{{group.title}}定義的內容--> {{group.content}} </accordion-group> <accordion-group heading="顯示添加商品"> <p>添加商品的細節</p> <button class="btn btn-default btn-md" ng-click="add()">添加</button> <div ng-repeat="beer in products">{{beer}}</div> </accordion-group> <accordion-group is-open="status.open"><!--默認顯示是關閉的--> <accordion-heading> 娛樂 <i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': status.open,'glyphicon-chevron-right': !status.open}"></i> </accordion-heading> 遊戲,動漫,電影,ktv... </accordion-group> </accordion> </div> </div> </div> </div> </body> </html>
Accordion.js var APP = angular.module('app', ['ui.bootstrap']); APP.controller('ctrl', ['$scope', function($scope) { $scope.oneAtATime = true; $scope.groups = [{ title: '飲料', content: 'beer,flavor,pure water' }, { title: '食物', content: 'bread,rice,meat' }]; $scope.products = ['beer1', 'beer2', 'beer3'];//定義只有3個元素的數組 $scope.add = function() { var no = $scope.products.length + 1;//實現每點擊一次長度自動加1 $scope.products.push('beer ' + no); }; // $scope.status = {//status能夠本身定義,也可使用angular ui內部封裝定義 //isOpen: true, //isDisabled: true // }; } ])
頁面顯示:
默認頁面
點擊打開娛樂
點擊獲取權限-"你叫什麼名字"變成灰色,不可選
11,單指令解析
ng-submit和ng-click
ng-submit在上面的form表單提交中已經提到過了,我在這裏寫了一個小demo來演示ng-submit和ng-click的做用
submit.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>ngSubmit demo</title> </head> <body> <form ng-submit="submit()" ng-controller="ctrl"><!--ng-submit是在js中定義的函數,提交form後要作什麼動做--> 把mk加到數組mikes裏面去: <input type="text" ng-model="mk" name="mk" /><!--The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.--> <input type="submit" value="提交" /> <pre>mikes集合裏面的內容:{{mikes}}</pre> <pre>mk輸入的內容: {{mk}}</pre> </form> <button ng-click="i = i * 324" ng-init="i=1"> 點擊增長: </button> <span> 每次累乘324:{{i}} </span> </body> <script src="js/angular.js"></script> <script src="js/submit.js"></script> </html>
submit.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.mikes = [];//定義數組 $scope.mk = '';//將這個mk利用ng-model綁定到html輸入框中,設定默認值 $scope.submit = function() { if ($scope.mk) { $scope.mikes.push(this.mk); $scope.mk = ''; } }; }]);
頁面樣式:
11.1,表單錯誤驗證
需求:表單錯誤的驗證input.$valid,input.$error,$valid,$error.required
form.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>ngSubmit demo</title> <style> .my-form { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-form.ng-invalid { background: rgb(0,255,81); width:700px; height:50px; } </style> </head> <body> <div style="width:700px;height:100px;"> <form name="myForm" ng-controller="ctrl" class="my-form"> 輸入驗證: <input name="input" ng-model="who" required> <span class="error" ng-show="myForm.input.$error.required">這是必填內容,請從新輸入</span><br> <hr> <code>用戶輸入記錄 = {{who}}</code><br> <p>判斷是否有用戶輸入</p> <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br> <p>判斷用戶輸入是否有錯誤出現</p> <code>myForm.input.$error = {{myForm.input.$error}}</code><br> <p>判斷用戶輸入form表單是否有效</p> <code>myForm.$valid = {{myForm.$valid}}</code><br> <p>判斷用戶輸入是否有錯誤表單驗證</p> <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br> </form> </div> </body> <script src="js/angular.js"></script> <script src="js/form.js"></script> </html>
form.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.who = 'mike';//定義表單的默認輸入項 }]);
頁面顯示展現:
當有內容輸入的時候:
當沒有內容輸入的時候:
11.2 input元素相關指令
type="error" $error.minlength $error.maxlength $error.required
input.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>input demo</title> </head> <body> <div ng-controller="ctrl"> <form name="mikeForm"> <label> 姓名: <input type="text" name="userName" ng-model="user.name" required> </label> <div role="alert"> <span class="error" ng-show="mikeForm.userName.$error.required">用戶名爲必填項,請輸入用戶名。</span> </div> <label> 公司: <input type="text" name="userCom" ng-model="user.com" ng-minlength="6" ng-maxlength="10"> </label> <div role="alert"> <span class="error" ng-show="mikeForm.userCom.$error.minlength">公司名字輸入過短</span> <span class="error" ng-show="mikeForm.userCom.$error.maxlength">公司名字輸入太長</span> </div> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>mikeForm.userName.$valid = {{mikeForm.userName.$valid}}</tt><br/> <tt>mikeForm.userName.$error = {{mikeForm.userName.$error}}</tt><br/> <tt>mikeForm.lastName.$valid = {{mikeForm.lastName.$valid}}</tt><br/> <tt>mikeForm.lastName.$error = {{mikeForm.lastName.$error}}</tt><br/> <tt>mikeForm.$valid = {{mikeForm.$valid}}</tt><br/> <tt>mikeForm.$error.required = {{!!mikeForm.$error.required}}</tt><br/> <tt>mikeForm.$error.minlength = {{!!mikeForm.$error.minlength}}</tt><br/> <tt>mikeForm.$error.maxlength = {{!!mikeForm.$error.maxlength}}</tt><br/> </div> </body> <script src="js/angular.js"></script> <script src="js/input.js"></script> </html>
input.js
var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.user = {name: 'mike', com: 'ibm'}; }]);
11.3 checkbox相關指令
ng-true-value="'YES'" ng-false-value="'NO'"
checkbox.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>checkBox demo</title> </head> <body> <form name="mikeForm" ng-controller="ctrl"> <label>Value1: <input type="checkbox" ng-model="checkBox.value1"> </label><br/> <label>Value2: <input type="checkbox" ng-model="checkBox.value2" ng-true-value="'YES'" ng-false-value="'NO'"> <!--ng-true-value="'YES'" ng-false-value="'NO'" 是定義checkBox的value值,顯示在頁面的--> </label><br/> <tt>value1 = {{checkBox.value1}}</tt><br/> <tt>value2 = {{checkBox.value2}}</tt><br/> </form> </body> <script src="js/angular.js"></script> <script src="js/submit.js"></script> </html>
checkbox.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.checkBox = {//定義默認值 value1 : true, value2 : 'YES' }; }]);
頁面演示效果:
11.4 日期控件
min和max不起做用
input.$error.date驗證不起做用
date.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>Date demo</title> </head> <body> <form name="mikeForm" ng-controller="ctrl"> <label for="dateInput">Pick a date in 2015:</label> <input type="date" id="dateInput" name="input" ng-model="mDate.value" placeholder="yyyy-MM-dd" min="2010-01-01" max="2015-12-31" required /> <div role="alert"> <span class="error" ng-show="mikeForm.input.$error.required">您輸入日期不符合要求,請從新輸入</span> <!--<span class="error" ng-show="mikeForm.input.$error.date">不是符合要求的日期,請從新輸入</span>--> </div> <tt>value = {{mDate.value | date: "yyyy/MM/dd"}}</tt><br/> <tt>mikeForm.input.$valid = {{mikeForm.input.$valid}}</tt><br/> <tt>mikeForm.input.$error = {{mikeForm.input.$error}}</tt><br/> <tt>mikeForm.$valid = {{mikeForm.$valid}}</tt><br/> <tt>mikeForm.$error.required = {{!!mikeForm.$error.required}}</tt><br/> </form> </body> <script src="js/angular.js"></script> <script src="js/date.js"></script> </html>
date.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.mDate = { value: new Date()//設定時間 }; }]);
頁面效果演示:
日期格式報錯:
11.5,郵件格式的輸入
type="email" <label>Email: <input type="email" name="input" ng-model="email.text" required> </label>
11.6 月份的輸入
<label for="exampleInput">Pick a month in 2013:</label> <input id="exampleInput" type="month" name="input" ng-model="example.value" placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
11.7 數值的輸入
<label>Number: <input type="number" name="input" ng-model="example.value" min="0" max="99" required>
11.8 radio 的輸入
radio僞代碼 $scope.specialValue = { "id": "12345", "value": "green" }; <label> <input type="radio" ng-model="color.name" ng-value="specialValue"> Green </label>
11.9 正則表達式驗證輸入
ng-trim="false":字符空格控制;
ng-pattern="example.word":正則表達式驗證輸入
validation.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>validation demo</title> </head> <body> <form name="myForm" ng-controller="ctrl"> <label>填寫一個沒有空格的英語單詞: <input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false"> </label> <div role="alert"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> 只有沒有空格的英文單詞才被容許!</span> </div> <tt>text = {{example.text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </body> <script src="js/angular.js"></script> <script src="js/validation.js"></script> </html>
validation.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.example = { text: 'word', word: /^\s*\w*\s*$/ }; }]);
頁面演示:
正確輸入:
錯誤輸入:
11.10 時間的輸入
<label for="exampleInput">Pick a between 8am and 5pm:</label> <input type="time" id="exampleInput" name="input" ng-model="example.value" placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
11.11 URL 的輸入
<label>URL: <input type="url" name="input" ng-model="url.text" required> <label>
11.12 week的輸入
<label>Pick a date between in 2013: <input id="exampleInput" type="week" name="input" ng-model="example.value" placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required /> </label>
11.13,ngBind
The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.ngBind告訴angular去實時替換html中text內容。
ngBind.html <!DOCTYPE html> <html ng-app="app"> <head> <meta Content-Type="html/text;charset=UTF-8"> <title>ngBind demo</title> </head> <body> <div ng-controller="ctrl"> <label>請輸入你的姓名: <input type="text" ng-model="name"></label><br> Hi,<span ng-bind="name"></span> </div> </body> <script src="js/angular.js"></script> <script src="js/ngBind.js"></script> </html>
ngBind.js var APP = angular.module('app', []) APP.controller('ctrl', ['$scope', function($scope) { $scope.name = 'AngularJs';//設定默認值 }]);
頁面顯示結果:
aliyun 開發的公共指令
公共頭(topbar)
公共導航(navbar)
truncateText(文本省略,處理特殊字符)
placeHolder
loading
wrapper for high charts
listSelector
simpleGrid(repeat,bindonce,searchBar,tableSearch,loading pagination,noDataInfo)
simpleForm
aliyunConsoleSpm
aliyunConsoleAside
numberRange
clipCopy
tableFixed
補充:
模式匹配(正則表達式)
使用ng-pattern="/PATTERN/"來確保輸入可以匹配指定的正則表達式:
<input type="text" ng-pattern="/[a-zA-Z]/" />
url輸入匹配
驗證輸入內容是不是URL,將input的類型設置爲 url:
<input type="url" name="homepage" ng-model="user.facebook_url" />
你們有問題歡迎進入羣討論:487768805