AngularJS 使用基礎知識
第一 迭代輸出之ng-repeat標簽
ng-repeat讓table ul ol等標簽和js里的數組完美結合
<ul><li ng-repeat="person in persons">{{person.name}} is {{person.age}} years old.</li></ul>你甚至可以指定輸出的順序:
<li ng-repeat="person in persons | orderBy:'name'">
第二 動態綁定之ng-model標簽 任何有用戶輸入,只要是有值的html標簽,都可以動態綁定js中的變量, 而且是動態綁定。
<input type="text" ng-model='password'>
對于綁定的變量,你可以使用{{}} 直接引用
<span>you input password is {{password}}</span>如果你熟悉fiter,你可以很容易的按你的需要格式輸出
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>第三 綁定點擊事件之ng-click事件
使用ng-click你可以很容易的為一個標簽綁定點擊事件。
<button ng-click="pressMe()"/>
當然前提是你要在$scope域中定義的自己的pressMe方法。
和傳統的onclick方法不同,你甚至可以為ng-click方法傳遞一個對象,就像這樣:
<ul><li ng-repeat="person in persons"><button ng-click="printf(person)"/></li></ul>
當然還有ng-dblclick標簽
第四 分支語句之ng-switch on、ng-if/ng-show/ng-hide/ng-disabled標簽
分支語句讓你在界面上都可以寫邏輯
<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 等標簽
表單中的輸入框,你可以使用上面的標簽來實現對用戶輸入的校驗。
從字面意思上你已經知道了它們的意思。
<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的存在。
新聞熱點
疑難解答
圖片精選