2016-12-30 47 views
1

我有一個選擇選項和幾個textareas在ng-repeat內,我想要做的是,當我從菜單中選擇一個選項時,相應的textareas集顯示屬於我剛纔選擇的一些信息。Angular JS - 如何更新控制器的ng-repeat信息?

而不是這樣做所有用ng-repeat創建的textareas都顯示信息。

這裏的鏈接到的jsfiddle可能更好地解釋這個問題: https://jsfiddle.net/711yvm8g/5/

這裏的HTML代碼:

<div ng-app="App"> 
    <div ng-controller="Ctrl"> 
     <div ng-repeat="data in carData"> 
     <select ng-model = "carSelected" ng-change = "changeInfo(carSelected)" data-ng-options = "car as car.name for car in cars"> 
     <option value = "">Select car</option> 
     </select> 

     <textarea>{{colorData}}</textarea> 
     <textarea>{{yearData}}</textarea> 
    </div> 

而這裏的Javascript代碼:

angular.module('App', []); 

function Ctrl($scope) { 
    //This carData object was created only to make the ng-repeat show multiple instances of the fields. 
    $scope.carData = { 
     a:"abc", 
     b:"def" 
    } 

    $scope.cars = [{ 
     name: "Volvo" 
    }, { 
     name: "Saab" 
    }] 

    var volvoInfo = { 
     color:"Blue", 
     year:"2016" 
    } 

    var saabInfo = { 
     color:"Red", 
     year:"2015" 
    } 

    $scope.changeInfo = function(carSelected) { 
     if(carSelected.name == "Volvo") { 
      $scope.colorData = volvoInfo.color; 
      $scope.yearData = volvoInfo.year; 
     } else { 
      $scope.colorData = saabInfo.color; 
      $scope.yearData = saabInfo.year; 
     } 
    } 
} 

有沒有辦法解決這個問題?非常感謝。

+0

,而不是'$ scope',所以有重複的每一個實例。然而,這意味着'$ scope.carData'確實需要是一個對象數組,而不是一個具有字符串屬性的對象。 – Claies

回答

1

你應該調整你的代碼中使用對象的數組。這樣就更容易管理。

angular.module('App', []); 
 

 
function Ctrl($scope) { 
 
    let carInfoModel = { 
 
    name: '', 
 
    color: '', 
 
    year: '', 
 
    } 
 
    $scope.cars = [angular.copy(carInfoModel),angular.copy(carInfoModel)] 
 

 
    $scope.carsInfo = [{ 
 
    name: 'Volvo', 
 
    color: 'Blue', 
 
    year: "2016" 
 
    }, { 
 
    name: 'Saab', 
 
    color: 'Red', 
 
    year: "2015" 
 
    }] 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="App"> 
 
    <div ng-controller="Ctrl"> 
 
    <div ng-repeat="data in cars"> 
 
     <select ng-model="data" data-ng-options="car as car.name for car in carsInfo"> 
 
     <option value="">Select car</option> 
 
     </select> 
 
     <textarea>{{data.color}}</textarea> 
 
     <textarea>{{data.year}}</textarea> 
 
    </div> 
 
    </div> 
 
</div>

實際上要結合各自`data`對象的輸入框
0

嘗試Ctrl.colorData和Ctrl.yearData您的textarea綁定