【问题标题】:Call a function in loop循环调用函数
【发布时间】:2018-02-16 03:53:07
【问题描述】:

问题是我有一个列表人员及其城市 ​​ID。我想通过一个函数从另一个 list 中根据他们的 id 获取城市名称。

<table class="table">
<tr>
<th>#</th>
<th>Name</th>
<th>Type</th>
<th>City</th>
</tr>

<tr ng-repeat="item in samples">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.type}}</td>
<td>{{getCity(item.city)}}</td>
</tr>
</table>

和控制器:

$scope.samples = [
{id: 1, name: "alex", type: "Average", city: 12},
{id: 2, name: "Alex", type: "Average", city: 12},
{id: 3, name: "Mia", type: "Medium", city: 13},
{id: 4, name: "Sasha", type: "Top", city: 14},
{id: 5, name: "Eric", type: "Top", city: 12},
{id: 6, name: "Taz", type: "Average", city: 14},
{id: 7, name: "Normai", type: "Low", city: 13},
{id: 8, name: "Jim", type: "Average", city: 11}];


$scope.city = [
{id: 11, name: "Dallas"},
{id: 12, name: "Los Angeles"},
{id: 13, name: "New York"},
{id: 14, name: "Washington"}
];

$scope.getCity = function(name) { 
angular.forEach($scope.city, function(value, key){

  if(value.id == name){
    $scope.city_name = value.name;
  }
  return $scope.city_name;
  });
}

这里是Fiddle了解更多详情。

【问题讨论】:

  • 你能看看我的回答吗

标签: angularjs


【解决方案1】:

试试这个功能

$scope.getCity = function(id) {
  var city = $scope.city.filter(function(c){ return angular.equals(c.id, id); })[0];
  return city.name;
}

【讨论】:

    【解决方案2】:

    你在错误的地方返回值。我只是更新了 jsfiddle you can check here

    这是代码的变化。

    $scope.getCity = function(name) {  
       $scope.city_name = "";
      angular.forEach($scope.city, function(value, key){ 
          if(value.id == name){
            $scope.city_name = value.name;
          } 
       });
      return $scope.city_name;
    }
    
    }]);
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2015-03-11
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2016-04-01
      相关资源
      最近更新 更多