【MVVM】- AngularJS 過濾器用法

過濾器做用:對model的數據進行加工,按照相應的格式進行顯示數組

AngularJS的過濾器和Avalon的用法差很少,一通百通。app

  • currency 格式化數字爲貨幣格式
  • filter 從數組項中選擇一個子集
  • lowercase 格式化字符串爲小寫
  • orderBy 根據某個表達式排列數組
  • uppercase 格式化字符串爲大寫

外觀界面code

<body ng-app="myApp">

<p>字符串大小過濾</p>
<div ng-controller="personCtrl">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>

<!-- 表達式過濾和avalon的過濾方法同樣 -->
小寫姓: {{firstName | lowercase }}<br>
大寫名:{{lastName | uppercase }}
</div>

<hr>
<p>數字貨幣化處理</p>
<div ng-init="quantity=3;cost=5">
總價:{{quantity*cost | currency}}
</div>

<hr>
<p>普通數組排序</p>
<div ng-init="nums=[0,5,6,3]">
<ol>

<!-- angular引擎先對數組元素進行升序排列,而後再遍歷顯示,也能夠對對象數組的屬性進行排序 -->
<li ng-repeat="item in nums | orderBy:item">{{item}}</li>
</ol>
</div>

<hr>
<p>對象數組排序</p>
<div ng-init="persons=[{'name':'zhangsan','age':'20'},
                     {'name':'lisi','age':'19'},
                     {'name':'wangwu','age':'39'}]">

<ol>
<!-- 年齡從小到大進行排序顯示 -->
<li ng-repeat="item in persons | orderBy:'age'">{{item}}</li>
</ol>
</div>

<hr>
<p>輸入過濾:</p>
<p><input type="text" ng-model="test"></p>
<ul>
  <!-- fileter:test--將輸入框的值綁定test對象,test做爲persons數組的進行數值匹配,若是匹配上就顯示響應的成員 -->
  <li ng-repeat="x in persons | filter:test | orderBy:'age'">
    {{ (x.name | uppercase) + ', ' + x.age }}
  </li>
</ul>
</div>

js操做邏輯對象

var app = angular.module('myApp', []);
    app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {  
        return $scope.firstName + " " + $scope.lastName;
    }
});

效果:blog

相關文章
相關標籤/搜索