Angularjs 我可以只在过滤器中重复,但只保留一个元素吗?

Angularjs 我可以只在过滤器中重复,但只保留一个元素吗?,angularjs,Angularjs,您好,我想知道我是否可以在数组上使用ng repeat,但将其保留为1个元素,而是在属性中显示重复的对象 这是我当前的代码: <span ng-if='locations.length >= 2'>Several places</span> <span ng-if='locations.length <= 1' ng-repeat="location in locations">{{location.city}}</span> 我

您好,我想知道我是否可以在数组上使用ng repeat,但将其保留为1个元素,而是在属性中显示重复的对象

这是我当前的代码:

 <span ng-if='locations.length >= 2'>Several places</span>
 <span ng-if='locations.length <= 1' ng-repeat="location in locations">{{location.city}}</span>
我希望我的位置仅在title属性内重复。 现在当我这么做的时候:

<span ng-if='locations.length >= 2' ng-repeat="location in locations" title="{{location.city + ', '}}">Several pl..</span>
几个pl。。
我得到了以下代码,这并没有错,因为这就是我编写的代码:

<span title="New York ,">Several places</span>
<span title="Dallas ,">Several places</span>
<span title="Los Angeles ,">Several places</span>
几个地方
几个地方
几个地方

但这不是我想要我的代码去做的,但我真的找不到如何去做我想做的事情。如何实现位置中的项目仅在title属性中重复?

我认为实现所需的最好方法是在控制器中创建一个变量(因为您没有提到任何关于
位置的内容,所以我假设:

var locations = [
  {city: 'New York'}, 
  {city: 'Dallas'}, 
  {city: 'Los Angeles'}
]

$scope.locationsTitle = locations.map(obj => obj.city).toString(); // 'New York,Dallas,Los Angeles'

现在,您可以在视图中使用
locationsTitle
来获得所需内容:)

只需给出各种答案,您还可以通过指令实现所需内容。此示例将使其具有灵活性,以便您可以将任何对象集合传递给指令,并指定对象上用于标题的属性

指示

html

几个地方

在控制器中定义一种方法,将所有城市名称连接在一起,如下所示

$scope.concatAllCityNames = function(locations) {
    var allCityNames = "";
    angular.forEach(locations, function(location ,index){
        allCityNames =  allCityNames + location.city;
        if(index < locations.length-1) {
          allCityNames =  allCityNames + ", ";
        }
    });
   return allCityNames;
}
或者,您可以在检索位置时将$scope变量中的所有城市名称连接起来,并从title属性访问它,如下所示

<span ng-if='locations.length >= 2' title="{{concatAllCityNames(locations)}}" >Several places</span>
<span ng-if='locations.length >= 2' title="{{allCityNames}}" >Several places</span>
几个地方
$scope.concatAllCityNames = function(locations) {
    var allCityNames = "";
    angular.forEach(locations, function(location ,index){
        allCityNames =  allCityNames + location.city;
        if(index < locations.length-1) {
          allCityNames =  allCityNames + ", ";
        }
    });
   return allCityNames;
}
<span ng-if='locations.length >= 2' title="{{concatAllCityNames(locations)}}" >Several places</span>
<span ng-if='locations.length >= 2' title="{{allCityNames}}" >Several places</span>