标签:
久闻AngularJS大名,只可惜一直未鼓起勇气学习,今天脑袋一热,收集资料开始了学习之旅。
AngularJS在我脑子里的印象,就是那对大括号了
AngularJS 表达式
AngularJS 表达式写在双大括号内:{{ expression }}。
类似于 JavaScript 表达式,AngularJS 表达式可以包含字母,操作符,变量。
与 JavaScript 表达式不同,AngularJS 表达式可以写在 HTML 中。
与 JavaScript 表达式不同,AngularJS 表达式不支持条件判断,循环及异常。
与 JavaScript 表达式不同,AngularJS 表达式支持过滤器。
注:数学运算必须要用单独的圆括号包裹。
例1: {{‘a=‘ + (1+1)}}
结果:a = 2
例2:{{‘a=‘ + 1+1}}
结果:a = 11
AngularJS 中的数据绑定,同步了 AngularJS 表达式与 AngularJS 数据。
ng-bind="name" 是通过 ng-model="name" 进行同步。
<p>在输入框中尝试输入:</p> <p>姓名: <input type="text" ng-model="name"></p> <p>您输入了:<b ng-bind="name"></b></p>
ng-repeat 指令会重复一个 HTML 元素
例1:数组循环绑定
<h4>简单循环:</h4> <select> <option ng-repeat="i in [0, 1, 2, 3, 4, 5, 6, 7]">{{i}}</option> </select>
例2:无序列表循环绑定+筛选+排序+控制器示例;
ng-controller 指令定义了应用程序控制器,一个应用中可以有多个控制器,某一控制器的相关元素必须在控制器的子元素集中。
orderBy:根据某个表达式排列数组。
filter:从数组项中选择一个子集。
currency:格式化数字为货币格式。
<ul ng-controller="PhoneListCtrl"> <li>全文筛选:<input ng-model="query"> 排序:<select ng-model="orderProp"> <option value="name">name asc</option> <option value="age">age asc</option> </select></li> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul>
var app = angular.module(‘DemoApp‘, []); app.controller(‘PhoneListCtrl‘,function ($scope) { $scope.phones = [ {"name": "2Nexus S", "snippet": "Fast just got faster with Nexus S.","age": 3}, {"name": "3Motorola XOOM™ with Wi-Fi", "snippet": "The Next, Next Generation tablet.Has Wifi","age": 2}, {"name": "1MOTOROLA XOOM™", "snippet": "The Next, Next Generation tablet.","age": 1} ]; //默认排序 $scope.orderProp = ‘name‘; });
例3:获取远程数据绑定Table+点击列头排序+操作按钮生成示例;
ng-click定义了一个事件,通过此事件改变序列的排序;
$http.get获取远程数据,可以是json或text/plain
表格可以通过odd和even进行奇偶行控制
<table class="table" ng-controller="UserListCtrl"> <thead> <tr> <th></th> <th ng-click="OrderClick(‘name‘)">用户名</th> <th ng-click="OrderClick(‘email‘)">邮件地址</th> <th ng-click="OrderClick(‘mobile‘)">手机</th> <th ng-click="OrderClick(‘logins‘)">登录次数</th> <th>操作</th> </tr> </thead> <tbody> <tr ng-repeat="user in users | filter:queryUser | orderBy:userOrder"> <td>{{ $index + 1 }}</td> <td>{{user.name}}</td> <td>{{user.email}}</td> <td>{{user.mobile}}</td> <td>{{user.logins}}</td> <td><a ng-href="Modify.asp?ID={{user.id}}">编辑</a> | <a ng-href="Delete.asp?ID={{user.id}}">删除</a></td> </tr> </tbody> </table>
app.controller(‘UserListCtrl‘, function($scope, $http) { $http.get("UserData.asp") .success(function(response) { $scope.users = response.records; $scope.userOrder = ‘mobile‘; }); $scope.OrderClick = function(field){ $scope.userOrder = field; }; });
表单示例:
<div ng-app="DemoApp" ng-controller="formCtrl"> <form novalidate> 用户名:<br> <input type="text" ng-model="user.name"><br> 邮件地址:<br> <input type="text" ng-model="user.email"> <br><br> <button ng-click="save()">Save</button> <button ng-click="reset()">RESET</button> </form> </div>
app.controller(‘formCtrl‘, function($scope, $http) { $scope.master = {name: "admin1", email: "admin@bomboo.com"}; $scope.save = function(){ $http.post("UserSave.asp",$scope.user) .success(function(response){ alert(‘成功保存了‘ + response); }); }; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); });
此时点击保存,发现服务端并没有收到任何POST提交的东西,这是因为AngularJS提交的数据为JSON格式,而不是jquery式的form格式,我们需要重写一个httpProvider改变其提交数据的方式
function normalProvider($httpProvider) { $httpProvider.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘; $httpProvider.defaults.headers.put[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘; var param = function(obj) { var query = ‘‘, name, value, fullSubName, subName, subValue, innerObj, i; for(name in obj) { value = obj[name]; if(value instanceof Array) { for(i=0; i<value.length;i++){ subValue = value[i]; fullSubName = name + ‘[‘ + i + ‘]‘; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + ‘&‘; } } else if(value instanceof Object) { for(subName in value) { subValue = value[subName]; fullSubName = name + ‘[‘ + subName + ‘]‘; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + ‘&‘; } } else if(value !== undefined && value !== null) query += encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value) + ‘&‘; } return query.length ? query.substr(0, query.length - 1) : query; }; $httpProvider.defaults.transformRequest = [function(data) {return angular.isObject(data) && String(data) !== ‘[object File]‘ ? param(data) : data; }]; };
修改模块初始化语句
var app = angular.module(‘DemoApp‘, [], normalProvider);
表单验证示例:
<h4>表单验证示例</h4> <form name="myForm" novalidate ng-submit="submitForm();"> <h3>Basic example</h3> <div class="form-section"> <p>Username:</p> <input type="text" name="username1" ng-model="username1" required /> <input type="submit" ng-disabled="myForm.username1.$pristine || myForm.username1.$dirty && myForm.username1.$invalid"> <div class="custom-error" ng-show="myForm.username1.$dirty && myForm.username1.$invalid">Invalid: <span ng-show="myForm.username1.$error.required">Username is required.</span> </div> <p>Email:</p> <input type="email" name="email1" ng-model="email1" required /> <input type="submit" ng-disabled="myForm.email1.$pristine || myForm.email1.$dirty && myForm.email1.$invalid"/> <div class="custom-error" ng-show="myForm.email1.$dirty && myForm.email1.$invalid">Invalid: <span ng-show="myForm.email1.$error.required">Email is required.</span> <span ng-show="myForm.email1.$error.email">Please, write a valid email address.</span> </div> </div> </form>
AngularJS支持HTML5验证及自定义的验证类型
<input type="text" ng-model="{string}" [name="{string}"] [required] [ng-required="{string}"] [ng-minlength="{number}"] [ng-maxlength="{number}"] [ng-pattern="{string}"] [ng-change="{string}"]> <input type="text" required /> <input type="text" ng-minlength=5 /> <input type="text" ng-maxlength=20 /> <input type="text" ng-pattern="/a-zA-Z/" /> <input type="email" name="email" ng-model="user.email" /> <input type="url" name="homepage" ng-model="user.facebook_url" />
自定义验证:
<input type="text" name="username" ng-model="username" ng-pattern="/^[a-zA-Z0-9]{4,10}$/" ng-命令="tableDB.userDBField" />
.directive(‘ngUnique‘, [‘$http‘, function ($http) { return { require: ‘ngModel‘, link: function (scope, elem, attrs, ctrl) { elem.on(‘blur‘, function (evt) { scope.$apply(function () { $http({ method: ‘POST‘, url: ‘backendServices/checkUsername.php‘, data: { username:elem.val(), dbField:attrs.ngUnique } }).success(function(data, status, headers, config) { ctrl.$setValidity(‘unique‘, data.status); }); }); } } } ]);
表单验证状态
//未被修改 myForm.email1.$pristine; //已被修改 myForm.email1.$dirty // Boolean. True if the user has already modified the form. //通过验证 myForm.email1.$valid //未通过验证 myForm.email1.$invalid // 错误,可能是以下情况: // { required: false, pattern:true } // or { required: false, email:true } myForm.email1.$error
PS:AngularJS 1.0.1版支持IE8,以后的表示都不支持了,悲催。。
标签:
原文地址:http://www.cnblogs.com/blackice/p/5051723.html