• angularjs directive(指令用法)将int转化成string


    1)将int转化成string

    a)angularjs select在ng-model值为int的时候无法实现双向绑定

    b)通过directive(指令用法)将int转化成string就能实现双向绑定

    1. DOCTYPE html>
    2. <html ng-app="my_app">
    3. <head>
    4. <script src="angular.min.js">script>
    5. <script type="text/javascript">
    6. var app = angular.module("my_app", []);
    7. app.controller('my_controller', function($scope) {
    8. $scope.type = 2;
    9. $scope.typeList = [{
    10. code: 1,
    11. name: '分期付款'
    12. }, {
    13. code: 2,
    14. name: '一次性付款'
    15. }];
    16. }).directive("toString", function() {
    17. return {
    18. restrict: "A",
    19. require: "ngModel",
    20. link: function(scope, elem, attr, ngModelCtr) {
    21. ngModelCtr.$formatters.push(function(viewValue) {
    22. if (typeof viewValue != "undefined") {
    23. return viewValue.toString();
    24. }
    25. })
    26. }
    27. }
    28. });
    29. script>
    30. head>
    31. <body ng-controller="my_controller">
    32. <select ng-model="type" to-String>
    33. <option ng-repeat="item in typeList" value="{{item.code}}">
    34. {{item.name}}
    35. option>
    36. select>
    37. body>
    38. html>

    2)将string转化成int

    a)angularjs input=number在ng-model值为string的时候无法实现双向绑定

    b)通过directive(指令用法)将string转化成int就能实现双向绑定

    1. DOCTYPE html>
    2. <html ng-app="my_app">
    3. <head>
    4. <script src="angular.min.js">script>
    5. <script type="text/javascript">
    6. var app = angular.module("my_app", []);
    7. app.controller('my_controller', function($scope) {
    8. // 绑定值是数字
    9. $scope.value1 = 1.1;
    10. // 绑定值是字符串
    11. $scope.value2 = '2.2';
    12. }).directive('stringToNumber', function() {
    13. return {
    14. require: 'ngModel',
    15. link: function(scope, element, attrs, ngModel) {
    16. ngModel.$parsers.push(function(value) {
    17. return '' + value;
    18. });
    19. ngModel.$formatters.push(function(value) {
    20. if (value)
    21. return Number(value);
    22. return value;
    23. });
    24. }
    25. };
    26. });
    27. script>
    28. head>
    29. <body ng-controller="my_controller">
    30. <input type="number" ng-model="value1" />
    31. <input type="number" ng-model="value2" string-to-number/>
    32. body>
    33. html>

  • 相关阅读:
    Elasticsearch 之 join 关联查询及使用场景
    (JavaSE)抽象类和接口
    Git、node、npm、webpack、yarn、脚手架是什么
    云原生周刊 | 波音公司允许员工给开源项目做贡献
    java中集合遍历方法的选择
    spring webflux的简单使用
    业务脚本pytest封装
    Java面试题大全带答案
    1186: 奖学金(结构体专题)
    Android10之Video MediaCodec硬解码流程(二十七)
  • 原文地址:https://blog.csdn.net/czh4869623/article/details/133030603