AngularJS 最常用指令的功能

在这里我整理了一下 AngularJS 中常用到的指令,包含它们的书写格式及指令的用法,功能。不过这里的整理有些不完整,不过在后面的使用过程中会逐步的去完善,里面有些知识点是摘录自网络上的,但是我都去调试检验代码的可行性,加以自己的理解去整理,有些部分加上了自己的理解。

第一 迭代输出之ng-repeat标签
ng-repeat让table ul ol等标签和js里的数组完美结合

 
  
  1.  
    •      ng-repeat="person in persons">
    •         {{person.name}} is {{person.age}} years old.
    •     

你甚至可以指定输出的顺序:

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

第二 动态绑定之ng-model标签
任何有用户输入,只要是有值的html标签,都可以动态绑定js中的变量,
而且是动态绑定。

 
  
  1.   type="text" ng-model='password'>

对于绑定的变量,你可以使用{{}} 直接引用

 
  
  1.  you input password is {{password}}

如果你熟悉fiter,你可以很容易的按你的需要格式输出

 
  
  1.  {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}

第三 绑定点击事件之ng-click事件
使用ng-click你可以很容易的为一个标签绑定点击事件。

 
  
  1.   ng-click="pressMe()"/>

当然前提是你要在$scope域中定义的自己的pressMe方法。
和传统的onclick方法不同,你甚至可以为ng-click方法传递一个对象,就像这样:

 
  
  1.  
    •      ng-repeat="person in persons">
    •          ng-click="printf(person)"/>
    •     

当然还有ng-dblclick标签

第四 分支语句之ng-switch on、ng-if/ng-show/ng-hide/ng-disabled标签
分支语句让你在界面上都可以写逻辑判断。

 
  
  1.  
    •      ng-repeat="person in persons">
    •         
    •          ng-switch on="person.sex">
    •              ng-switch-when="1">you are a boy
    •              ng-switch-when="2">you are a girl
    •         
    •         
    •          ng-if="person.sex==1">you may be a father
    •         
    •          ng-show="person.sex==2">you may be a mother
    •         
    •             please input your baby's name: type="text" ng-disabled="!person.hasBaby"/>
    •         
    •     

第五 校验语法之 ng-trim ng-minlength ng-maxlength required ng-pattern 等标签
这块在实践练习,发现之前记录太简单,而这部分涉及到的内容比较丰富,所以要另起一篇日记来记录,请点《AngularJS 自带表单验证的使用》来查看

第六 下拉框之 ng-options 标签
ng-options是为下拉框专门打造的标签。

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

下拉框中显示的是person.name,当你选中其中一个的时候,你可以通过yourSelected得到你选中的person.id.

第七 控制css之 ng-style 标签
ng-style帮你轻松控制你的css属性

 
  
  1.   ng-style="myColor">your color

你可以通过给myColor赋值的形式来改变你想要的效果,就像这样:
$scope.myColor={color:’blue’};
$scope.myColor={cursor: ‘pointer’,color:’blue’};

第八 异步请求之 $http 对象。
AngularJS 提供了一个类似jquery的$.ajax的对象,用于异步请求。
在AngularJS中对异步操作是推崇至极的,所以$http的操作都是异步的不像jquery.ajax里还提供了async参数。

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

如果你是POST请求,params里的数据会帮你拼到url后面,data里的数据会放到请求体中。

转载请注明:PKCMS博客 » AngularJS 最常用指令的功能

你可能感兴趣的:(前端)