首页  >  文章  >  web前端  >  AngularJS变量及过滤器Filter用法分析

AngularJS变量及过滤器Filter用法分析

高洛峰
高洛峰原创
2016-12-05 17:06:411050浏览

本文实例讲述了AngularJS变量及过滤器Filter用法。分享给大家供大家参考,具体如下:

1. 关于部分变量的操作

设置变量:

ng-init="hour=14" //设置hour变量在DOM中 使用data-ng-init 更好些
$scope.hour = 14; //设置hour变量在js中

   

使用变量:

(1) 如果是在DOM 相关的 ng-*** 属性里 直接写变量名

如:

<p ng-show="hour > 13">I am visible.</p>

   

(2) 如果是在控制器HTML 中但是不在 ng属性里

使用{{变量名}}

如:

{{hour}}

   

(3) 当然第三种就是上面的 在js中使用

加上对象名 $scope.

$scope.hour

   

(4) 在表单控件中 ng-model中的变量 可以直接

同时在 html 中 使用 {{变量名}}

<p>Name: <input type="text" ng-model="name"></p>
<p>You wrote: {{ name }}</p>

   

还可以通过 ng-bind 属性进行变量绑定

<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

   

(5) 可以直接在ng的属性 或变量中使用表达式

会自动帮你计算 需要符合js语法

ng-show="true?false:true"
{{5+6}}
<div ng-app="" ng-init="points=[1,15,19,2,40]">
  <p>The third result is <span ng-bind="points[2]"></span></p>
</div>

   

2. js中的变量循环

<div ng-app="" ng-init="names=[&#39;Jani&#39;,&#39;Hege&#39;,&#39;Kai&#39;]">
 <ul>
  <li ng-repeat="x in names">
   {{ x }}
  </li>
 </ul>
</div>

   

3.变量的过滤 filter

Filter         Description
currency    以金融格式格式化数字
filter          选择从一个数组项中过滤留下子集。
lowercase   小写
orderBy     通过表达式将数组排序
uppercase   大写

如:

<p>The name is {{ lastName | uppercase }}</p>

   

当然多个函数封装可以使用 |

<p>The name is {{ lastName | uppercase | lowercase }}</p>
//排序函数的使用
<ul>
 <li ng-repeat="x in names | orderBy:&#39;country&#39;">
  {{ x.name + &#39;, &#39; + x.country }}
 </li>
</ul>
//通过输入内容自动过滤显示结果
<div ng-app="" ng-controller="namesCtrl">
  <p><input type="text" ng-model="test"></p>
  <ul>
   <li ng-repeat="x in names | filter:test | orderBy:&#39;country&#39;">
    {{ (x.name | uppercase) + &#39;, &#39; + x.country }}
   </li>
  </ul>
</div>

   

names | filter:test | orderBy:'country'
就是将names数组中的项 按照 test表单值进行 筛选
然后以 names中的子元素 country 进行排序

自定义过滤器:

<!DOCTYPE html>
<html ng-app="HelloApp">
<head>
<title></title>
</head>
<body ng-controller="HelloCtrl">
 <form>
   <input type="text" ng-model="name"/>
 </form>
 <div>{{name|titlecase}}</div>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <script type="text/javascript">
  // 编写过滤器模块
  angular.module(&#39;CustomFilterModule&#39;, [])
      .filter( &#39;titlecase&#39;, function() {
    return function( input ) {
      return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
  }
  });
  // 实际展示模块
  // 引入依赖的过滤器模块 CustomFilterModule
  angular.module(&#39;HelloApp&#39;, [ &#39;CustomFilterModule&#39;])
    .controller(&#39;HelloCtrl&#39;, [&#39;$scope&#39;, function($scope){
    $scope.name = &#39;&#39;;
  }])
</script>
</body>
</html>

   


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn