Mobile first! Wijmo 5 + Ionic Framework之:費用跟蹤 App


費用跟蹤應用采用了Wijmo5和Ionic Framework創建,目的是構建一個hybird app。

我們基於《Mobile first! Wijmo 5 + Ionic Framework之:Hello World!》的環境,將在本教程中完成費用跟蹤App的構建。下面的代碼結構是本教程完成要達到的效果,請預先創建好文件和目錄。

www/                     --> 工程根目錄
  index.html         --> app 布局文件 (主HTML文件)
  css/                   --> css 目錄
  js/                    --> javascript 目錄
    app.js               --> 主模塊
    app.routes.js        --> 主路由模塊
    controllers/         --> app控制器目錄
    models/                 --> app模塊目錄
    services/        --> app 數據Service目錄
  templates/             --> angularJs視圖代碼目錄(通過UI-Router調用) 
  lib/           --> 第三方類庫, 包括Ionic, Wijmo, jQuery等

 

數據模型(Data Model)

在費用跟蹤App中,我們先要創建Data Model,E-R圖如下

etErdDiagram-300x145

 

  • Category:開支分類
  • Expense:開支記錄
  • Budget: 預算(下面會用到)

在代碼中,我們需要在www/js/services構建AngularJs Services來對數據模型進行建模。我們會用到HTML5的localStorage進行數據本地存儲, 采用的格式為JSON。 需要注意的是,HTML5本地存儲只能存字符串,任何格式存儲的時候都會被自動轉為字符串,所以讀取的時候,需要自己進行類型的轉換。目前我們實現的是HTML5 本地存儲,有興趣的讀者還可移植為RESTful API、SQLite等數據存儲方法。

運行demo后,通過Chrome調試查看的本地存儲截圖:

image

瀏覽開支歷史記錄

在開支歷史頁面中,提供了2個功能:瀏覽開支歷史記錄、刪除開支記錄。為了實現這些功能,在www\js\controllers\history.js文件中,添加如下代碼:

//從localStorage獲得開支數據
$scope.expenses = ExpenseSvc.getExpensesWithCategory();

這行代碼提供了返回本地存儲的開支記錄。ExpenseSvc 服務,不僅返回了開支對象,同時也返回了開支分類。基於這些數據,在

www\templates\history.tpl.htm文件中,在ion-context指令內添加Ionic的ion-list指令,代碼如下:

<ion-view title="History">
  <ion-nav-buttons side="right">
    <a class="button button-icon icon ion-plus" href="#/app/create"></a>
  </ion-nav-buttons>
  <ion-content class="has-header">
    <ion-list>
      <ion-item ng-repeat="expense in expenses | orderBy:'date':reverse track by expense.id" class="item item-icon-left">
        <i class="icon ion-record {{ expense.category.cssClass }}"></i>
        <div class="row">
          <div class="col-50">
            <h2>{{ expense.title }}</h2>
          </div>
          <div class="col-25">
            <small class="light-grey">{{ expense.date | date: 'shortDate' }}</small>
          </div>
          <div class="col-25">
            {{ expense.amount | currency }}
          </div>
        </div>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

 

ion-list指令,用於生成排序的HTML列表,其子標簽ion-item指令用於生成HTML列表項。 在ngRepeat指令中,我們使用了“track by”,目的是在對開支集合修改時提升性能,相關教程可參考博客《Using Track-By With ngRepeat In AngularJS 1.2 》。

現在添加刪除開支記錄按鈕,用於向左滑動出現刪除按鈕、點擊刪除可刪除開支記錄。

在ion-item標簽關閉前添加ion-option-button標簽,代碼如下:

<ion-option-button class="button button-assertive" on-tap="confirmDelete(expense.id)">Delete</ion-option-button>

ion-option-button 是Ionic提供的另一個指令,用於在ion-item指令內試用。默認的,ion-option-button 是隱藏的,當在ion-item內向左滑動,則按鈕會可見。這個功能尤其對小屏幕設備非常重要。另外,還可通過該指令內置的can-swipe來實現對這個權限的管理--如有的用戶不允許刪除操作權限。

在刪除函數中(控制器),可看到代碼片段如下:

function confirmDelete(expenseId) {
   // delete expense by its id property
   $scope.expenses = ExpenseSvc.deleteExpense(expenseId);
}

通過這個代碼,我們調用ExpenseSvc服務的deleteExpense進行刪除指定的開支記錄(expenseId),同時這個方法也會返回開支記錄集合用於更新頁面數據。在真實的場景中,刪除記錄返回整個集合不是最理想的,但在此處我們用於演示說明。可動手試着刪除幾行數據試試。

image

另外,在刪除這種比較危險的操作中,應該需要添加對話框再次提醒一下用戶。這里我們使用了Ionic提供的$ionicActionSheet service服務來實現。更新www\js\controllers\history.js控制器代碼的confirmDelete函數如下:

//刪除開支記錄
$scope.confirmDelete = function (expenseId) {
  //ionic的 確認對話框
  // show()函數返回了一個函數,用於隱藏actionSheet
  var hideSheet = $ionicActionSheet.show({
    titleText: 'Are you sure that you\'d like to delete this expense?',
    cancelText: 'Cancel',
    destructiveText: 'Delete',
    cancel: function () {
      // 如果用戶選擇cancel, 則會隱藏刪除按鈕
      $ionicListDelegate.closeOptionButtons();
    },
    destructiveButtonClicked: function () {
      // 通過id刪除開支記錄
      $scope.expenses = ExpenseSvc.deleteExpense(expenseId);

      // 隱藏對話框
      hideSheet();
    }
  });
};

ionicActionSheet服務提供了自定義接口,可實現各種提示對話框。上面代碼實現的提示對話框效果截圖如下:

 image

 

創建開支記錄

點擊History頁面右上角的image可實現手工創建一條新的開支記錄。在www\templates\createExpense.tpl.htm文件中,代碼如下:

<ion-view title="Create">
    <ion-content class="has-header padding">
        <form name="frmCreate">
            <div class="custom-form-list list">
                <label class="item item-input">
                    <i class="icon ion-alert-circled placeholder-icon assertive" ng-show="!frmCreate.title.$pristine && frmCreate.title.$invalid"></i>
                    <input name="title" type="text" placeholder="Title" ng-model="expense.title" ng-maxlength="55" required>
                </label>
                <wj-input-number value="expense.amount" min="0" step="5" format="c2"></wj-input-number>
                <wj-calendar value="expense.date"></wj-calendar>                
                <wj-combo-box items-source="categories" 
                              display-member-path="htmlContent"
                              selected-value-path="id"
                              selected-value="expense.categoryId" 
                              is-editable="false" 
                              is-content-html="true"></wj-combo-box>
                <label class="item item-input">
                    <textarea placeholder="Description" ng-model="expense.description"></textarea>
                </label>
            </div>
            <div class="button-bar">
                <button type="button" class="button button-dark icon-left ion-close" on-tap="cancel()">Cancel</button>
                <button type="button" class="button button-balanced icon-left ion-checkmark" on-tap="addExpense()" ng-disabled="frmCreate.title.$invalid">Save</button>
            </div>
        </form>
    </ion-content>
</ion-view>

這里使用ion-view 和 ion-content 指令進行內容展現。然后再添加Form,用ng-show指令驗證輸入內容---Wijmo的指令已經在輸入門限做了限制,故不需要驗證。同時Wijmo Calendar 和InputNumber應該是自解釋,ComboBox中可能不是。

ComboBox關聯數據模型中的開支分類,我們通過其itemsSource屬性進行數據綁定。ComboBox的displayMemberPath 用於設置顯示內容,selectedItem的selectedValue用於選擇開支分類的id屬性。

在createExpense 控制器中,可看到如下的代碼片段:

// 初始化Expense object
$scope.expense = new Expense('', 0, new Date(), '', null);

// 獲得HTML類型的開支分類
$scope.categories = CategorySvc.getCategoriesWithHtmlContent();

// 用localStorage存儲開支數據
$scope.addExpense = function () {
  // insert expense
  ExpenseSvc.insertExpense($scope.expense);
  $scope.cancel();
};

// 取消方法 (如,可回到主頁面)
$scope.cancel = function () {
  $state.go('app.overview');

};

上面的第一行代碼用於初始化一個開支記錄,用Expense的構造函數來實現,並賦值給$scope.expense對象。 開支分類,通過調用CategorySvc服務的接口,從localStorage獲得數組。addExpense 方法用於提交新增的開支記錄,同樣用到了ExpenseSvc服務。最后一個函數$scope.canel使用了UI Router的 $state 服務,導航到主頁面。

運行app,截圖如下:

image

Details Grid

在前面幾節中,我們分別學習了如何查看、創建、刪除開支記錄。在本節,我們將通過Wijmo5的FlexGrid和CollectionView批量對開支記錄進行呈現,打開detailsGrid 模板文件,添加如下代碼片段:

<ion-view title="Details Grid">
  <!-- set overflow-scroll="true" and hand scrolling to native -->
  <ion-content class="has-header" overflow-scroll="true">
    <wj-flex-grid auto-generate-columns="false" items-source="data" selection-mode="Row" row-edit-ending="rowEditEnding(s,e)" style="position:relative">
      <wj-flex-grid-column width="2*" min-width="250" header="Title" binding="title"></wj-flex-grid-column>
      <wj-flex-grid-column width="*" min-width="100" header="Amount" binding="amount" format="c2"></wj-flex-grid-column>
      <wj-flex-grid-column width="*" min-width="100" header="Date" binding="date"></wj-flex-grid-column>
      <wj-flex-grid-column width="2*" min-width="250" header="Description" binding="description"></wj-flex-grid-column>
    </wj-flex-grid>
  </ion-content>
  <ion-footer-bar class="bar button-bar-footer">
    <div class="button-bar">
      <button type="button" class="button button-dark icon-left ion-close" on-tap="cancel()">Cancel</button>
      <button type="button" class="button button-balanced icon-left ion-checkmark" ng-disabled="!data.itemsEdited.length" on-tap="update()">Save</button>
    </div>
  </ion-footer-bar>
</ion-view>

在FlexGrid指令下面,我們添加了2個按鈕,Cancel和Save,分別用於當點擊的時候進行取消和存儲操作,數據存儲於localStorage。其中,Save按鈕的默認不可用,通過ngDisabled的表達式進行控制。

FlexGrid 指令,用於在模板內生成Wijmo5的FlexGrid 控件。我們使用itemsSource 進行數據源綁定,同時通過autoGenerateColumns=”false”關閉自動生成數據列,以及SelectMode類型為整行Row。同時也設置了FlexGrid的rowEditEnding事件,用於驗證數據輸入。在FlexGrid內部,定義了Columns,分別指定了header、binding、width。

如下代碼是detailsGrid 控制器片段:

// 通過localStorage獲得開支記錄數據,並初始化CollectionView
$scope.data = new wijmo.collections.CollectionView(ExpenseSvc.getExpenses());

// CollectionView的變更可跟蹤
$scope.data.trackChanges = true;

// 批量更新開支記錄
$scope.update = function () {
  // make sure items have been edited
  if ($scope.data.itemsEdited.length) {
    // bulk update expenses
    ExpenseSvc.updateExpenses($scope.data.itemsEdited);

    // return to overview page
    $scope.cancel();
  }
};

// 取消方法 (如導航到主頁面)
$scope.cancel = function () {
  $state.go('app.overview');
};

// FlexGrid.rowEditEnding事件處理
$scope.rowEditEnding = function (sender, args) {
  var expense = $scope.data.currentEditItem,      // get expense being edited
      isValid = isExpenseValid(expense);          // validate expense

  // if the expense isn't valid, cancel the edit operation
  if (!isValid) {
    $scope.data.cancelEdit();
    return;
  }
};

// 驗證函數:確保開支記錄數據合法有效
function isExpenseValid(expense) {
  return expense &&
         expense.title !== '' &&
         expense.title.length < 55 &&
         wijmo.isNumber(expense.amount) &&
         wijmo.isDate(expense.date) &&
         expense.amount >= 0;
}

上面代碼的第一行,通過從localStorage 加載數據,然后初始化CollectionView的對象,繼而賦值給$scope.data對象,用於給前端HTML進行Data-Source綁定數據源。

接下來看cancel、update方法,cancel方法和上面的一樣,使用了UI Router的$state服務進行回到首頁。update方法,先進行數據判斷,通過核查$scope.data.itemsEdited.length是否有效(是否有開支記錄變更),然后再調用ExpenseSvc 進行數據修改,對localStorage數據進行存儲處理。

最后,FlexGrid的rowEditEnding事件觸發了rowEditEnding函數,即當row修改完成后尚未cancel、update前觸發。在這里進行有效性判斷,若無效則cancel並返回。這里,我們使用了Wijmo 5提供的工具函數:isNumber和isDate來進行判斷。

運行Details Grid截圖如下:

image

 

概述

修改app.routes.js 文件,從默認的history頁面到overview頁面:

$urlRouterProvider.otherwise('/app/history');

to:

$urlRouterProvider.otherwise('/app/overview');

這個細小的改變使得UI Router 會對沒有明確重定向的,均會導向overview頁面。

overview頁面代碼如下所示:

<ion-view title="Overview">
  <ion-nav-buttons side="right">
    <a class="button button-icon icon ion-plus" href="#/app/create"></a>
  </ion-nav-buttons>
  <ion-content class="has-header padding">
    <div ng-show="hasExpenses">
      <hgroup class="text-center padding-vertical">
        <h2 class="title">
          <span ng-class="expensesCssClass">{{ totalExpenses | currency }}</span> of {{ budget | currency }}
        </h2>
        <h4>{{ budgetMsg }}</h4>
      </hgroup>
      <wj-flex-chart items-source="categories"
                     chart-type="Bar" binding-x="name"
                     tooltip-content=""
                     selection-mode="Point"
                     footer="Tap the chart's bars to see history by category"
                     selection-changed="selectionChanged(s)"
                     item-formatter="itemFormatter"
                     style="height: 400px;">
        <wj-flex-chart-series binding="total"></wj-flex-chart-series>
        <wj-flex-chart-axis wj-property="axisX" format="c0"></wj-flex-chart-axis>
        <wj-flex-chart-axis wj-property="axisY" reversed="true" major-grid="false" axis-line="true"></wj-flex-chart-axis>
      </wj-flex-chart>
    </div>
    <div ng-hide="hasExpenses">
      <h4 class="padding text-center">You haven't added any expenses yet!  Click the <i class="icon ion-plus"></i> button to get started!</h4>
    </div>
  </ion-content>
</ion-view>

上面的代碼,首先使用hgroup元素呈現了開支記錄的總和。下面接着使用了Wijmo 5 FlexChart 渲染了每個開支分類的開支金額,在FlexChart 指令內,我們指定了一些屬性,如數據序列、x、y軸,同時當點擊Bar的時候會觸發FlexChart的plot elements 事件,對當前分類詳情做列表呈現。

上面這些功能的實現,基於overview.js文件的邏輯:

// 通過BudgetSvc服務,獲得localStorage數據
$scope.budget = BudgetSvc.getBudget();

// 判斷是否有開支記錄,返回bool
$scope.hasExpenses = ExpenseSvc.hasExpenses();

// 獲得開支的總金額
$scope.totalExpenses = ExpenseSvc.getExpenseTotal();

// 獲得各個分類的小計金額
$scope.categories = ExpenseSvc.getCategoriesExpenseSummary();

// 初始化CSS 樣式
$scope.expensesCssClass = 'energized';

//設置開支金額顯示字符串
// NOTE: use $filter service to format the total prior to concatenating the string
$scope.budgetMsg = $scope.totalExpenses <= $scope.budget
                        ? $filter('currency')($scope.budget - $scope.totalExpenses).concat(' until you reach your monthly limit')
                        : $filter('currency')($scope.totalExpenses - $scope.budget).concat(' over your monthly limit');

//設置開支css樣式
$scope.expensesCssClass = 0 === $scope.totalExpenses
                ? 'dark'
                : $scope.totalExpenses === $scope.budget
                     ? 'energized'
                     : $scope.totalExpenses > $scope.budget
                          ? 'assertive'
                      : 'balanced';

//*** FlexChart's selectionChanged event handler
$scope.selectionChanged = function (sender) {
  var category = null;
  if (sender.selection && sender.selection.collectionView.currentItem) {
      // get the currently selected category
      category = sender.selection.collectionView.currentItem;

      // navigate to the category history page to display expenses for selected category
      $state.go('app.category-history', { category: category.slug });
  }
};

//*** set color of FlexChart's plot elements
$scope.itemFormatter = function (engine, hitTestInfo, defaultFormat) {
  if (hitTestInfo.chartElement === wijmo.chart.ChartElement.SeriesSymbol) {
      // set the SVG fill and stroke based on the category's bgColor property
      engine.fill = hitTestInfo.item.bgColor;
      engine.stroke = hitTestInfo.item.bgColor;
      defaultFormat();
  }

};

 

預覽截圖如下:

image

 

下載地址

 

相關閱讀:

開放才能進步!Angular和Wijmo一起走過的日子

Angular vs React 最全面深入對比

Wijmo已率先支持Angular4 & TypeScript 2.2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM