AngularJS变量及过滤器Filter用法分析
本文实例讲述了AngularJS变量及过滤器Filter用法。分享给大家供大家参考,具体如下:
1.关于部分变量的操作
设置变量:
ng-init="hour=14"//设置hour变量在DOM中使用data-ng-init更好些 $scope.hour=14;//设置hour变量在js中
使用变量:
(1)如果是在DOM相关的ng-***属性里直接写变量名
如:
<png-show="hour>13">Iamvisible.</p>
(2)如果是在控制器HTML中但是不在ng属性里
使用{{变量名}}
如:
{{hour}}
(3)当然第三种就是上面的在js中使用
加上对象名$scope.
$scope.hour
(4)在表单控件中ng-model中的变量可以直接
同时在html中使用{{变量名}}
<p>Name:<inputtype="text"ng-model="name"></p>
<p>Youwrote:{{name}}</p>
还可以通过ng-bind属性进行变量绑定
<p>Name:<inputtype="text"ng-model="name"></p> <png-bind="name"></p>
(5)可以直接在ng的属性或变量中使用表达式
会自动帮你计算需要符合js语法
ng-show="true?false:true"
{{5+6}}
<divng-app=""ng-init="points=[1,15,19,2,40]">
<p>Thethirdresultis<spanng-bind="points[2]"></span></p>
</div>
2.js中的变量循环
<divng-app=""ng-init="names=['Jani','Hege','Kai']">
<ul>
<ling-repeat="xinnames">
{{x}}
</li>
</ul>
</div>
3.变量的过滤filter
Filter Description
currency 以金融格式格式化数字
filter 选择从一个数组项中过滤留下子集。
lowercase 小写
orderBy 通过表达式将数组排序
uppercase 大写
如:
<p>Thenameis{{lastName|uppercase}}</p>
当然多个函数封装可以使用|
<p>Thenameis{{lastName|uppercase|lowercase}}</p>
//排序函数的使用
<ul>
<ling-repeat="xinnames|orderBy:'country'">
{{x.name+','+x.country}}
</li>
</ul>
//通过输入内容自动过滤显示结果
<divng-app=""ng-controller="namesCtrl">
<p><inputtype="text"ng-model="test"></p>
<ul>
<ling-repeat="xinnames|filter:test|orderBy:'country'">
{{(x.name|uppercase)+','+x.country}}
</li>
</ul>
</div>
names|filter:test|orderBy:'country'
就是将names数组中的项按照test表单值进行筛选
然后以names中的子元素country进行排序
自定义过滤器:
<!DOCTYPEhtml>
<htmlng-app="HelloApp">
<head>
<title></title>
</head>
<bodyng-controller="HelloCtrl">
<form>
<inputtype="text"ng-model="name"/>
</form>
<div>{{name|titlecase}}</div>
<scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<scripttype="text/javascript">
//编写过滤器模块
angular.module('CustomFilterModule',[])
.filter('titlecase',function(){
returnfunction(input){
returninput.replace(/\w\S*/g,function(txt){returntxt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase();});
}
});
//实际展示模块
//引入依赖的过滤器模块CustomFilterModule
angular.module('HelloApp',['CustomFilterModule'])
.controller('HelloCtrl',['$scope',function($scope){
$scope.name='';
}])
</script>
</body>
</html>
希望本文所述对大家AngularJS程序设计有所帮助。