使用angular更新json值

updating a json value with angular

本文关键字:json 更新 angular 使用      更新时间:2023-09-26

我正在尝试使用angular从文本框更新json对象值,但我不确定最好的方法是什么。

这是json对象。。。

   $scope.productAttributes = {
        "CostRequirements":[
            {
                "OriginPostcode": 'NW1BT',
                "BearerSize":100
            }
        ]
    }

当用户键入文本字段并单击按钮时,我想获取该文本字段值并将其传递到json对象中,以替换我试图在范围变量中传递的postcose值(OriginPostcode),但没有成功。

 <input type="text" placeholder="Please enter postcode" class="form-control" ng-model="sitePostcode"/>

这是当用户单击按钮提交json 时激发的函数

var loadPrices = function () {
        productsServices.getPrices1($scope.productAttributes)
            .then(function (res) {
                $scope.selectedProductPrices = res.data.Products;
               // $scope.selectedProductAddOns = res.data.product_addons;
            })
            .finally(function () {
                $scope.loadingPrices = false;
                $scope.loadedPrices = true;
            });
    };

有人能告诉我需要做什么才能将文本框中的用户输入放入json对象吗?

非常感谢

我们没有看到的是使用按钮运行更新的函数。它应该看起来像这个

// your HTML button
<button ng-click='updateThingy()'>Update</button>
// your HTML input
<input type="text" ng-model="myObject.sitePostcode"/>

// your controller
$scope.myObject = { // ties to the ng-model, you want to tie to a property of an object rather than just a scope property
    sitePostcode : $scope.productAttributes.CostRequirements[0].OriginPostcode // load in post code from productAttributes
}; 
$scope.updateThingy = function(){
    $scope.productAttributes.CostRequirements[0].OriginPostcode = $scope.myObject.sitePostcode;
};

这里有一个演示plunker,用于在点击按钮时更新值,希望它能有所帮助。

http://plnkr.co/edit/8PsVgWbr2hMvgx8xEMR1?p=preview

我猜loadPrices函数在您的控制器中。那么,您应该在控制器和函数中有可用的sitePostCode变量。因此,您只需要在$scope.productAttributes.中注入该值

$scope.productAttributes.sitePostCode = $scope.sitePostCode;

在调用productsServices.getPrices1之前,您需要先将其放置。

var loadPrices = function() {
    $scope.productAttributes.sitePostCode = $scope.sitePostCode;
    productsServices.getPrices1($scope.productAttributes)
    .then(function(res) {
        $scope.selectedProductPrices = res.data.Products;
        // $scope.selectedProductAddOns = res.data.product_addons;
    })
    .finally(function() {
        $scope.loadingPrices = false;
        $scope.loadedPrices = true;
    });
};

如果有效,请告诉我。