2015-02-06 128 views
2

我正在尝试使用角度更新来自文本框的json对象值,我不确定最好的方法是什么。以角度更新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对象?

非常感谢

+0

似乎有从你的解释缺少的组件......你有东西在你的代码。例如角度控制器和按钮来查看如何分配它来运行该功能。 – SoluableNonagon 2015-02-06 16:38:46

+0

抱歉 - loadPrices和productAttributes坐在同一个控制器中。 – 2015-02-06 16:40:38

+0

我更新了我的答案,它显示了一种方法,可以正确地从作用域'抓取'值,并通过单击按钮来更新json。 – SoluableNonagon 2015-02-06 16:58:53

回答

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

这里是一个演示plunker更新按钮单击值,希望它帮助了。

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

+1

非常感谢您抽出时间来创建一个plunker。它的工作现在。正如你所看到的,我有很多东西需要学习,但是要知道有些人愿意帮助你。谢谢! – 2015-02-06 17:04:33

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

让我知道它是否工作。

+0

但$ scope.productAttributes.sitePostCode未更新对象值'OriginPostcode' – 2015-02-06 16:52:24