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.
  • 相关阅读:
    XML节点处理
    Log4Net使用记录
    WPF选择文件夹及文件操作
    SQL 一些语句记录
    一篇MSSQL事务的测试文章
    游标示例
    WPF实现多线程加载数据
    MS SQL索引学习
    Entity Framework 利用 Database.SqlQuery<T> 执行存储过程,并返回Output参数值
    手持移动端特殊链接:打电话,发短信,发邮件
  • 原文地址:https://www.cnblogs.com/echo2016/p/5681371.html
Copyright © 2011-2022 走看看