2015-09-21 90 views
0

比方说,我有一个下降淹死名单,我在我的HTML模板动态地添加:角度:通过复式值控制器

<button type="button" ng-click="addRow()" style="margin-bottom:5px;">Add cities </button> 
    <div ng-repeat="city in cities"> 
    <select ng-model="cities_$index" 
      ng-options="n.id as n.name for n in citiesList" 
      class="form-control" 
     ng-required="true"> 
    <option value="">-- Choose City --</option> 
           </select> 
    </div> 

角控制器:

$scope.addRow = function() { 
var newrow = []; 
if ($scope.cities.length === 0) { 

       newrow.push({ 'cities': $scope.cities_0 }); 
      } 
      else { 
       $scope.cities.forEach(function (row, key) { 

        var city= '$scope.cities_'+key; // in php i can do this 
//but i dont know how to do it with Js/Angular 

        console.log('row' + city); 

        newrow.push({ 'cities': city}); 

        console.log(newrow); 
       }); 
      } 
$scope.cities.push(newrow); 
} 

我想这检索来自所选城市的值,但我有未定义的值。

$scope.send = function() { 

      angular.forEach($scope.cities, function (value, key) { 

       console.log(value.id); // the id from the ng-options 
     }; 

在常规的HTML代码,我只加name="city"和我检索所有在我的输入框中添加的城市。但是我怎么能从我的控制器中的ng模型中检索出城市呢?

我知道我做错了什么,但因为我是新的角度我试图!

谢谢

+0

难道它只是'数据'在你的情况下,将持有阵列? – Steve

+0

请包含您的控制器代码,以便我们不必假设任何内容。 – o4ohel

+0

我更新了我的第一个问题,并添加了控制器代码以更好地理解我的需求 – user708683

回答

0

假设的关键(市)为您的DATAS数组里面,你可以这样做:

<div ng-repeat="data in datas"> 
<input type="text">{{data.name}} 
</div> 
+0

我更新了第一个问题,以更好地理解我的需求。谢谢 – user708683

0

ng-model仍然是独一无二的。你在这里失踪的是ng-repeat为每个项目创建一个子范围。因此,ng-model的值对于每个子范围都是唯一的。 ng-model的行为与纯HTML输入不同,并且具有相同ng-model的多个输入只会指向内存中的同一对象。而不是像您在纯HTML输入中所期望的那样,将“加起来”的值添加到房产城市。

如果您正在使用的对象datasng-repeat,它是一种你<input />将绑定到的datas一个项目属性常见的做法。

<div ng-repeat="data in datas"> 
    <input type="text">{{data.city}} 
</div> 
+0

为了更好地理解我的需求,我更新了第一个问题。谢谢 – user708683

+0

保持添加新城市。使用ng-repeat仅显示所选城市的集合。 – ThiagoPXP