Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

AngularJS 開發指南(六):表單與 ngModel 雙向綁定詳解

表單控制項(input、select、textarea)負責取得使用者輸入,表單則是一組有關聯的控制項集合。

使用者能透過表單與控制項提供的驗證服務,得知自己的輸入是否合法,這讓互動變得友善。但別忘了:客戶端驗證很容易被繞過,因此絕不能完全依賴它——要建立安全的應用,伺服器端驗證依然不可或缺。

ngModel 是雙向綁定的關鍵

理解 AngularJS 雙向綁定,就必須理解 ngModel 指令。它動態地在 model 與 view 之間互相映射,从而实现雙向同步。

為了方便美化,ngModel 會自動為元素加上四個 CSS 類別:

  • ng-valid/ng-invalid:目前值是否合法。
  • ng-pristine/ng-dirty:使用者是否動過這個欄位。

一個表單就是 FormController 的實例,可透過 name 屬性選擇性公開到作用域;表單控制項則是 NgModelController 的實例,同樣能公開到作用域。這意味著視圖可以直接取得表單或控制項的狀態,據此決定要不要顯示某個按鈕或錯誤訊息。

完整範例

<!doctype html>
<html ng-app>
<head>
  <script src="https://code.angularjs.org/angular-1.0.2.min.js"></script>
  <script>
    function Controller($scope) {
      $scope.master = {};
      $scope.update = function(user) {
        $scope.master = angular.copy(user);
      };
      $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
      };
      $scope.isUnchanged = function(user) {
        return angular.equals(user, $scope.master);
      };
      $scope.reset();
    }
  </script>
</head>
<body>
  <div ng-controller="Controller">
    <form name="form" class="css-form" novalidate>
      <!-- novalidate 用來屏蔽瀏覽器本身的驗證功能 -->
      Name:
      <input type="text" ng-model="user.name" name="uName" required /><br />
      E-mail:
      <input type="email" ng-model="user.email" name="uEmail" required /><br />
      <div ng-show="form.uEmail.$dirty && form.uEmail.$invalid">
        Invalid:
        <span ng-show="form.uEmail.$error.required">Tell us your email.</span>
        <span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
      </div>
      Gender:
      <input type="radio" ng-model="user.gender" value="male" />male
      <input type="radio" ng-model="user.gender" value="female" />female<br />
      <input type="checkbox" ng-model="user.agree" name="userAgree" required />
      I agree:
      <input ng-show="user.agree" type="text" ng-model="user.agreeSign" required /><br />
      <div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div>
      <button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button>
      <button ng-click="update(user)"
              ng-disabled="form.$invalid || isUnchanged(user)">SAVE</button>
    </form>
  </div>
</body>
</html>

SAVE 鈕的條件值得細看:form.$invalid 為真(整份表單有任何欄位未通過驗證)或 isUnchanged(user) 為真(內容沒變動)時,按鈕就不可點擊。

自訂驗證器

AngularJS 已實作大部分 HTML5 輸入型別(text、number、url、email、radio、checkbox)與驗證指令(required、pattern、minlength、maxlength、min、max)。若要自訂驗證,做法是寫一個指令並在其中取得 ngModel 的控制器,驗證函數可以掛在兩個位置:

  • 模型到視圖——只要綁定的模型改變,$formatters 陣列中的函數會被輪流呼叫,每個函數都有機會格式化資料,也能透過 $setValidity 改變驗證狀態。
  • 視圖到模型——使用者與表單互動時,$setViewValue 會被呼叫,接著 $parsers 陣列中的函數依序執行,每個函數都能改寫值或設定驗證狀態。
<!doctype html>
<html ng-app="form-example1">
<head>
  <script src="https://code.angularjs.org/angular-1.0.2.min.js"></script>
  <script>
    var app = angular.module('form-example1', []);

    var INTEGER_REGEXP = /^\-?\d+$/;   // 可有負號,後面皆為整數
    app.directive('integer', function() {
      return {
        require: 'ngModel',            // 依賴 ngModel 指令
        link: function(scope, elm, attrs, ctrl) {
          ctrl.$parsers.unshift(function(viewValue) {
            if (INTEGER_REGEXP.test(viewValue)) {
              ctrl.$setValidity('integer', true);
              return viewValue;
            } else {
              ctrl.$setValidity('integer', false);
              return undefined;
            }
          });
        }
      };
    });

    var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;  // 正負皆可,整數浮點皆可
    app.directive('smartFloat', function() {
      return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
          ctrl.$parsers.unshift(function(viewValue) {
            if (FLOAT_REGEXP.test(viewValue)) {
              ctrl.$setValidity('float', true);
              return parseFloat(viewValue.replace(',', '.'));
            } else {
              ctrl.$setValidity('float', false);
              return undefined;
            }
          });
        }
      };
    });
  </script>
</head>
<body>
  <div ng-controller="Controller">
    <form name="form" class="css-form" novalidate>
      <div>
        Size (integer 0 - 10):
        <input type="number" ng-model="size" name="size" min="0" max="10" integer />
        {{size}}<br />
        <span ng-show="form.size.$error.integer">This is not valid integer!</span>
        <span ng-show="form.size.$error.min || form.size.$error.max">
          The value must be in range 0 to 10!
        </span>
      </div>
      <div>
        Length (float):
        <input type="text" ng-model="length" name="length" smart-float />
        {{length}}<br />
        <span ng-show="form.length.$error.float">This is not a valid float number!</span>
      </div>
    </form>
  </div>
</body>
</html>

這裡建立了兩個指令:integer 驗證輸入是否為整數(1.23 因為含小數部分而不合格);smart-float 則把「1.2」或「1,2」都轉成合法的浮點數 1.2。之所以不能用 type="number",正是因為支援 HTML5 的瀏覽器不允許使用者輸入「1,2」這種值。

自訂表單控制項

AngularJS 已實作所有基本控制項,對多數場景足夠。若要做自己的控制項並與 ngModel 協同運作,需要兩件事:

  • 實作 render 方法。模型變化時,值會先經過 $formatters,再由 render 負責在視圖上呈現新資料。
  • 在使用者與控制項互動、模型需要更新時呼叫 $setViewValue,這通常在 DOM 監聽事件中完成。

以下示範一個「內容可編輯」元素,並讓它與模型雙向綁定:

<!doctype html>
<html ng-app="form-example2">
<head>
  <script src="https://code.angularjs.org/angular-1.0.2.min.js"></script>
  <script>
    angular.module('form-example2', [])
      .directive('contenteditable', function() {
        return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
            // view -> model
            elm.bind('blur', function() {
              scope.$apply(function() {
                ctrl.$setViewValue(elm.html());
              });
            });

            // model -> view
            ctrl.$render = function(value) {
              elm.html(value);
            };

            // 從 DOM 載入初始值
            ctrl.$setViewValue(elm.html());
          }
        };
      });
  </script>
</head>
<body>
  <div contentEditable="true" ng-model="content" title="Click to edit">Some</div>
  <pre>model = {{content}}</pre>
  <style type="text/css">
    div[contentEditable] { cursor: pointer; background-color: #D0D0D0; }
  </style>
</body>
</html>

注意 blur 事件中的 scope.$apply 不可省略——DOM 事件發生在 AngularJS 上下文之外,不經 $apply 的話,模型雖然變了,視圖卻不會更新。

Copyright © Linux教程網 All Rights Reserved