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(/\w\S*/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>







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值