AngularJS 使用基礎(chǔ)知識(shí)
第一 迭代輸出之ng-repeat標(biāo)簽
ng-repeat讓table ul ol等標(biāo)簽和js里的數(shù)組完美結(jié)合
<li ng-repeat="person in persons">
{{person.name}} is {{person.age}} years old.
</li>
</ul>
你甚至可以指定輸出的順序:
第二 動(dòng)態(tài)綁定之ng-model標(biāo)簽
任何有用戶輸入尽楔,只要是有值的html標(biāo)簽,都可以動(dòng)態(tài)綁定js中的變量砚偶,
而且是動(dòng)態(tài)綁定炮赦。
對(duì)于綁定的變量水醋,你可以使用{{}} 直接引用
如果你熟悉fiter癌蚁,你可以很容易的按你的需要格式輸出
第三 綁定點(diǎn)擊事件之ng-click事件
使用ng-click你可以很容易的為一個(gè)標(biāo)簽綁定點(diǎn)擊事件。
當(dāng)然前提是你要在$scope域中定義的自己的pressMe方法幔虏。
和傳統(tǒng)的onclick方法不同产喉,你甚至可以為ng-click方法傳遞一個(gè)對(duì)象捂掰,就像這樣:
<li ng-repeat="person in persons">
<button ng-click="printf(person)"/>
</li>
</ul>
當(dāng)然還有ng-dblclick標(biāo)簽
第四 分支語句之ng-switch on、ng-if/ng-show/ng-hide/ng-disabled標(biāo)簽
分支語句讓你在界面上都可以寫邏輯判斷镊叁。
<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>
第五 校驗(yàn)語法之ng-trim ng-minlength ng-maxlength required ng-pattern 等標(biāo)簽
表單中的輸入框尘颓,你可以使用上面的標(biāo)簽來實(shí)現(xiàn)對(duì)用戶輸入的校驗(yàn)。
從字面意思上你已經(jīng)知道了它們的意思晦譬。
<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 來判斷輸入的內(nèi)容是否滿足ng-pattern疤苹,ng-maxlength,maxlength
你通過$scope.userNum獲得的輸入內(nèi)容是去掉前后空白的敛腌,因?yàn)閚g-trim的存在卧土。
第六 下拉框之ng-options標(biāo)簽
ng-options是為下拉框?qū)iT打造的標(biāo)簽。
下拉框中顯示的是person.name像樊,當(dāng)你選中其中一個(gè)的時(shí)候尤莺,你可以通過yourSelected得到你選中的person.id.
第七 控制css之ng-style標(biāo)簽
ng-style幫你輕松控制你的css屬性
你可以通過給myColor賦值的形式來改變你想要的效果,就像這樣:
$scope.myColor={color:'blue'}; $scope.myColor={cursor: 'pointer',color:'blue'};
第八 異步請(qǐng)求之$http對(duì)象生棍。
AngularJS 提供了一個(gè)類似jquery的.ajax的對(duì)象颤霎,用于異步請(qǐng)求。 在AngularJS中對(duì)異步操作是推崇至極的涂滴,所以http的操作都是異步的不像jquery.ajax里還提供了async參數(shù)友酱。
.success(function(response, status, headers, config){
//do anything what you want;
})
.error(function(response, status, headers, config){
//do anything what you want;
});
如果你是POST請(qǐng)求,params里的數(shù)據(jù)會(huì)幫你拼到url后面柔纵,data里的數(shù)據(jù)會(huì)放到請(qǐng)求體中缔杉。