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

时间:2016-02-10 20:40:21

标签: javascript angularjs angular-ngmodel angular-controller

我有以下函数在您键入时每3个字符添加一个逗号,例如1000返回1,000

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

但该功能特定于该输入字段ng-model。如何以一种我可以在任何输入字段中重用该函数的方式将$scope.item.price的值返回给视图?例如在函数中使用x而不是item.price

也许使用return或者写一个指令,但不知道该怎么做。

HTML

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

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('.');
            }
        }
  }

我正在寻找的解决方案将是这样的:

<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
  }
}

例如,如下所示:

function double(x) {
  return x * 2
}

2 个答案:

答案 0 :(得分:0)

我认为最好的方法是将您的函数转换为指令:

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('.');
            }
          }
        });
      }
    }
  });

和HTML:

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

该指令&#34;绑定&#34;输入ng-model,监视更改并应用转换。

这是plunker

另外两个版本:directive which binds to item with price propertystand-alone directive with own template

答案 1 :(得分:0)

我有一个完整功能的指令,您可以在之后建模。

随意修改它以供自己使用,但它基本上可以实现您想要的功能并具有其他一些不错的功能。

指令:

<p>

模板:

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();
        }
    }
});

HTML引用指令:

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