简体   繁体   English

如何将数据传递到控制器并返回到Angular中的视图?

[英]How to pass data to controller and back to the view in Angular?

I have the following function that adds a comma every 3 characters as you type, so for example 1000 with return 1,000 我有以下函数,在您键入时每3个字符添加一个逗号,例如1000返回1,000

http://plnkr.co/edit/TL8hlIxyPbwUNCbLiKgs?p=preview http://plnkr.co/edit/TL8hlIxyPbwUNCbLiKgs?p=preview

But the function is specific to that input field's ng-model . 但是该函数特定于该输入字段的ng-model How do I return the value of $scope.item.price back to the view in a way that I can reuse the function with any input field? 如何以可在任何输入字段中重用函数的方式将$scope.item.price的值返回至视图? Such as using x instead of item.price in the function. 例如在函数中使用x代替item.price

Perhaps using return or maybe writing a directive, but not sure how to do that. 也许使用return或编写指令,但不确定如何执行。

HTML HTML

<input type="text" name='' ng-model='item.price' ng-change='addCommas(item)' />

JS JS

    $scope.addCommas = function(item){
        price = item.price
        if (price){
            $scope.item.price_clean = price = price.replace(/,/g, '')
            $scope.item.price = price.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
            if (price.indexOf('.') > -1) {
                varSplit = price.toString().split('.');
                varSplit[0] = varSplit[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
                varSplit[1] = varSplit[1].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
                $scope.item.price = varSplit.join('.');
            }
        }
  }

The solution I'm looking for would be something along these lines: 我正在寻找的解决方案将遵循以下原则:

<input ng-model="item.price" ng-change="addCommas(item.price)"/>

$scope.addCommas = function(x) {
  if (x) {
    // functions here, only working with 'x', not with item or price.
    return x
  }
}

Like, for example, the following: 例如,如下所示:

function double(x) {
  return x * 2
}

I think the best way is to convert your function into directive: 我认为最好的方法是将函数转换为指令:

app.directive('addCommas', function() {
    return {
      scope: {
          'ngModel': '='
      },
      link: function ($scope, element, attrs) {
        $scope.$watch('ngModel',function() {
          var value = $scope.ngModel.toString();
          //console.log(value)
          if (value){
            value = value.replace(/,/g, '')
            $scope.ngModel = value.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
            if (value.indexOf('.') > -1) {
              varSplit = value.toString().split('.');
              varSplit[0] = varSplit[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
              varSplit[1] = varSplit[1].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
              $scope.ngModel = varSplit.join('.');
            }
          }
        });
      }
    }
  });

And HTML: 和HTML:

 <input type="text" name='' ng-model='item.price' add-commas/>

The directive "binds" to the input's ng-model , watches for changes and applies the transformation. 指令“绑定”到输入的ng-model ,监视更改并应用转换。

Here is plunker . 这是朋克

Two more versions: directive which binds to item with price property and stand-alone directive with own template . 还有两个版本: 绑定到具有price属性的项目的 指令和带有自己的template的独立指令

I have a fully functioning directive you can model after. 我有一个功能齐全的指令,您可以在此之后进行建模。

Feel free to modify this for your own use but it basically accomplishes what you want and has some other nice features. 可以随意修改以供您自己使用,但是它基本上可以实现您想要的功能,并具有其他一些不错的功能。

Directive: 指示:

angular.module('maskModule').directive('maskTextbox', function ($filter) {
    return {
        restrict: 'E',
        templateUrl:'templates/mask-textbox.html',
        scope: {
            maskDisplayModel: '=?',
            maskModel: '=?',
            maskType: '@',
            maskCurrency: '@',
            placeHolder: '@'
        },
        link: function (scope, element, attr, ctrl) {
            scope.maskDisplayModel = "";
            if (!scope.maskCurrency)
                scope.maskCurrency = "$";
            var t;
            scope.timer = 1;

            if (!scope.placeHolder && scope.maskType == "phone") {
                scope.placeHolder = "Phone..."
            }

            if (!scope.placeHolder && scope.maskType == "currency") {
                scope.placeHolder = "Amount..."
            }

            if (!scope.placeHolder && (scope.maskType == "number" || scope.maskType == "decimal" || scope.maskType == "alpha")) {
                scope.placeHolder = "Type here..."
            }

            scope.countdown = function () {
                if (scope.timer == 0) {
                    scope.changeAction()
                } else {
                    scope.timer -= 1;
                    t = setTimeout(function () {
                        scope.countdown();
                    }, 750);
                }
            };

            scope.resetTimer = function () {
                scope.timer = 1;
                clearTimeout(t);
                scope.countdown();
            };

            scope.changeAction = function () {
                if (scope.maskType == "number") {
                    scope.maskModel = scope.maskDisplayModel.replace(/[^0-9]/g, '');
                    scope.maskDisplayModel = scope.maskDisplayModel.replace(/[^0-9]/g, '');
                }
                if (scope.maskType == "decimal") {
                    scope.maskModel = scope.maskDisplayModel.replace(/[^0-9.]/g, '');
                    scope.maskDisplayModel = scope.maskDisplayModel.replace(/[^0-9.]/g, '');
                }
                if (scope.maskType == "phone") {
                    scope.maskModel = scope.maskDisplayModel.replace(/[^0-9-()]/g, '');
                    scope.maskDisplayModel = scope.maskDisplayModel.replace(/[^0-9]/g, '');
                    scope.maskDisplayModel = $filter("tel")(scope.maskDisplayModel)
                }
                if (scope.maskType == "alpha") {
                    scope.maskModel = scope.maskDisplayModel.replace(/[^A-maska-mask]/g, '');
                    scope.maskDisplayModel = scope.maskDisplayModel.replace(/[^A-maska-mask]/g, '');
                }
                if (scope.maskType == "currency") {
                    scope.maskModel = scope.maskDisplayModel.replace(/[^0-9.]/g, '');
                    scope.maskDisplayModel = scope.maskDisplayModel.replace(/[^0-9.]/g, '');
                    scope.maskDisplayModel = $filter("currency")(scope.maskDisplayModel, scope.maskCurrency)
                }
            };

            scope.initiate = function () {
                if (scope.maskType == "number") {
                    scope.maskModel = scope.maskModel.replace(/[^0-9]/g, '');
                    scope.maskDisplayModel = scope.maskModel.replace(/[^0-9]/g, '');
                }
                if (scope.maskType == "decimal") {
                    scope.maskModel = scope.maskModel.replace(/[^0-9.]/g, '');
                    scope.maskDisplayModel = scope.maskModel.replace(/[^0-9.]/g, '');
                }
                if (scope.maskType == "phone") {
                    scope.maskModel = scope.maskModel.replace(/[^0-9-()]/g, '');
                    scope.maskDisplayModel = $filter("tel")(scope.maskModel);
                }
                if (scope.maskType == "alpha") {
                    scope.maskModel = scope.maskModel.replace(/[^A-Za-z]/g, '');
                    scope.maskDisplayModel = scope.maskModel.replace(/[^A-Za-z]/g, '');
                }
                if (scope.maskType == "currency") {
                    scope.maskModel = scope.maskModel.replace(/[^0-9.]/g, '');
                    scope.maskDisplayModel = $filter("currency")(scope.maskModel, scope.maskCurrency, 2);
                }

            };

            scope.initiate();
        }
    }
});

Template: 模板:

<input type="text" ng-model="maskDisplayModel" ng-blur="changeAction()" placeholder="{{placeHolder}}"/>

HTML referencing directive: HTML参考指令:

<mask-textbox mask-model="myText" mask-type="phone"></mask-textbox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Laravel 中,如何简单地将数据从 js 传递到 controller 返回查看? - In Laravel, how to simply pass data from js to controller back to view? 将数据从Angular模态的控制器传递回主控制器 - Pass data from an Angular modal's controller back to the main controller 如何将数据从视图文件传递到控制器? - How to pass data from view file to the controller? 如何将模型从视图传递到控制器,将项目添加到列表,传递回视图 - How to pass Model from View to Controller, add items to list, pass back to view 从角度控制器传回链接 - pass a link back from angular controller 如何在angularjs中将数据从对话框传回控制器? - how to pass back the data from dialog to controller in angularjs? 如何将控制器数据传递到组件中并在ember js中备份 - how to pass controller data into component and back up in ember js 如何以角度将数据从视图传递到布局 - How to pass data from view to layout in angular 如何将值从视图传递到Angular JS中的控制器? - How to pass a value from view to a controller in Angular JS? 如何将变量从html视图传递到角度控制器以按作用域访问 - How to pass variable from html view to angular controller to access by scope
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM