2015-02-06 69 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