用angular更新json值

时间:2015-02-06 16:27:32

标签: javascript json angularjs

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

这是json对象......

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

            }
        ]
    }

当一个用户键入文本字段并单击一个按钮时,我想获取该textfield值并将其传递给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对象时需要做些什么吗?

非常感谢

2 个答案:

答案 0 :(得分:3)

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

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

这是一个用于更新按钮点击值的演示插件,希望它有所帮助。

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

答案 1 :(得分:0)

我猜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;
    });
};

让我知道它是否有效。