AngularJS 最經常使用的八種功能

第一 迭代輸出之ng-repeat標籤
ng-repeat讓table ul ol等標籤和js裏的數組完美結合javascript

1
2
3
4
5
<ul>
<li ng-repeat="person in persons">
{{person.name}} is {{person.age}} years old.
</li>
</ul>

你甚至能夠指定輸出的順序:css

1
<li ng-repeat="person in persons | orderBy:'name'">

第二 動態綁定之ng-model標籤
任何有用戶輸入,只要是有值的html標籤,均可以動態綁定js中的變量,
並且是動態綁定。html

1
<input type="text" ng-model='password'>

對於綁定的變量,你可使用{{}} 直接引用java

1
<span>you input password is {{password}}</span>

若是你熟悉fiter,你能夠很容易的按你的須要格式輸出jquery

1
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>

第三 綁定點擊事件之ng-click事件
使用ng-click你能夠很容易的爲一個標籤綁定點擊事件。ajax

1
<button ng-click="pressMe()"/>

固然前提是你要在$scope域中定義的本身的pressMe方法。數組

和傳統的onclick方法不一樣,你甚至能夠爲ng-click方法傳遞一個對象,就像這樣:異步

1
2
3
4
5
<ul>
<li ng-repeat="person in persons">
<button ng-click="printf(person)"/>
</li>
</ul>

固然還有ng-dblclick標籤async

第四 分支語句之ng-switch on、ng-if/ng-show/ng-hide/ng-disabled標籤
分支語句讓你在界面上均可以寫邏輯判斷。ide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ul>
<li ng-repeat="person in persons">
<span ng-switch on="person.sex">
<span ng-switch-when="1">you are a boy</span>
<span ng-switch-when="2">you are a girl</span>
</span>
<span ng-if="person.sex==1">you may be a father</span>
<span ng-show="person.sex==2">you may be a mother</span>
<span>
please input your baby's name:<input type="text" ng-disabled="!person.hasBaby"/>
</span>
<span>
</li>
</ul>

第五 校驗語法之ng-trim ng-minlength ng-maxlength required ng-pattern 等標籤
表單中的輸入框,你可使用上面的標籤來實現對用戶輸入的校驗。
從字面意思上你已經知道了它們的意思。

1
2
3
<form name="yourForm">
<input type="text" name="inputText" required ng-trim="true" ng-model="userNum" ng-pattern="/^[0-9]*[1-9][0-9]*$/" ng-maxlength="6" maxlength="6"/>
</form>

你能夠經過 $scope.yourForm.inputText.$error.required 來判斷輸入框是否爲空
你能夠經過 $scope.yourForm.inputText.$invalid 來判斷輸入的內容是否知足ng-pattern,ng-maxlength,maxlength
你經過$scope.userNum得到的輸入內容是去掉先後空白的,由於ng-trim的存在。

第六 下拉框之ng-options標籤
ng-options是爲下拉框專門打造的標籤。

1
<select ng-model="yourSelected" ng-options="person.id as person.name in persons"></select>

下拉框中顯示的是person.name,當你選中其中一個的時候,你能夠經過yourSelected獲得你選中的person.id.

第七  控制css之ng-style標籤
ng-style幫你輕鬆控制你的css屬性

1
<span ng-style="myColor">your color</span>

你能夠經過給myColor賦值的形式來改變你想要的效果,就像這樣:

1
2
$scope.myColor={color:'blue'};
$scope.myColor={cursor: 'pointer',color:'blue'};

第八  異步請求之$http對象。
AngularJS 提供了一個相似jquery的$.ajax的對象,用於異步請求。
在AngularJS中對異步操做是推崇至極的,因此$http的操做都是異步的不像jquery.ajax裏還提供了async參數。

1
2
3
4
5
6
7
$http({method : 'POST',params : { id:123}, data:{name:'john',age:27}, url : "/mypath"})
.success(function(response, status, headers, config){
//do anything what you want;
})
.error(function(response, status, headers, config){
//do  anything what you want;
});

若是你是POST請求,params裏的數據會幫你拼到url後面,data裏的數據會放到請求體中。

相關文章
相關標籤/搜索