zoukankan      html  css  js  c++  java
  • ng-model值字符串转数值型(convertToNumber directive)

    <select ng-model="model.id" convert-to-number>
      <option value="0">Zero</option>
      <option value="1">One</option>
      <option value="2">Two</option>
    </select>
    {{ model }}
    angular.module('nonStringSelect', [])
    .run(function($rootScope) {
      $rootScope.model = { id: 2 };
    })
    .directive('convertToNumber', function() {
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
    //format text from the user (view to model)
    ngModel.$parsers.push(function(val) { return parseInt(val, 10); }); 
    //format text going to user (model to view)
    ngModel.$formatters.push(function(val) { return '' + val; }); } }; });

    Formatters Definition

    Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.

    Parsers Definition

    Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.

    To summarize:

    • Formatters change how model values will appear in the view.
    • Parsers change how view values will be saved in the model.
  • 相关阅读:
    20181113-2 每周例行报告
    20181030-4 每周例行报告
    20180925-5 代码规范,结对要求
    20181023-3 每周例行报告
    20181016-10 每周例行报告
    PSP总结报告
    作业要求 20181204-1 每周例行报告
    公开感谢
    附加作业 软件工程原则的应用实例分析
    作业要求 20181127-2每周例行报告
  • 原文地址:https://www.cnblogs.com/echo2016/p/5681371.html
Copyright © 2011-2022 走看看