gpt4 book ai didi

javascript - 如何在 Angular 中将数据传递到 Controller 并返回到 View ?

转载 作者:行者123 更新时间:2023-11-28 06:23:32 25 4
gpt4 key购买 nike

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

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

但该函数特定于该输入字段的 ng-model。如何将 $scope.item.price 的值返回到 View ,以便我可以在任何输入字段中重用该函数?例如在函数中使用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
}

最佳答案

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

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

该指令“绑定(bind)”到输入的 ng-model,监视更改并应用转换。

这里是plunker .

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

关于javascript - 如何在 Angular 中将数据传递到 Controller 并返回到 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com