本文实例讲述了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=['Jani','Hege','Kai']">
 <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:'country'">
  {{ x.name + ', ' + 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:'country'">
    {{ (x.name | uppercase) + ', ' + 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('CustomFilterModule', [])
      .filter( 'titlecase', function() {
    return function( input ) {
      return input.replace(/wS*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
  }
  });
  // 实际展示模块
  // 引入依赖的过滤器模块 CustomFilterModule
  angular.module('HelloApp', [ 'CustomFilterModule'])
    .controller('HelloCtrl', ['$scope', function($scope){
    $scope.name = '';
  }])
</script>
</body>
</html>

希望本文所述对大家AngularJS程序设计有所帮助。

点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部