Angularjs “显示”-&引用;如果值为空?

Angularjs “显示”-&引用;如果值为空?,angularjs,Angularjs,有没有办法这样说: <th ng-repeat=" o in Odds" >{{o.Name || "-"}}</th> <th ng-repeat=" o in Odds" > <span ng-if="o.Name">{{o.Name}}</span> <span ng-if="!o.Name"> - </span> </th> {{

有没有办法这样说:

<th ng-repeat=" o in Odds" >{{o.Name || "-"}}</th>
   <th ng-repeat=" o in Odds" >
        <span ng-if="o.Name">{{o.Name}}</span>        
        <span ng-if="!o.Name"> - </span>
   </th>
{{o.Name | |“-”}

因此,如果o.Name中没有数据显示“-”?

对于这种情况,您可以像这样使用ngIf:

<th ng-repeat=" o in Odds" >{{o.Name || "-"}}</th>
   <th ng-repeat=" o in Odds" >
        <span ng-if="o.Name">{{o.Name}}</span>        
        <span ng-if="!o.Name"> - </span>
   </th>

{{o.Name}}
- 

如果这不起作用,您可以使用一些东西

<th ng-repeat="o in Odds">
    <span ng-if="o.Name">{{o.Name}}</span>
    <span ng-if="!o.Name">-</span>
</th>

{{o.Name}}
-

您的示例应该可以运行,但是如果您在o.Name中有空格或函数,它将无法解析为,并且您将在HTML中得到一个不可见的空格,而不是所需的破折号

通用过滤器可用于将空值替换为破折号,并首先对输入应用各种规格化:

angular.module('App.filters', []).filter('placeholder', [function () {
    return function (text, placeholder) {
        // If we're dealing with a function, get the value
        if (angular.isFunction(text)) text = text();
        // Trim any whitespace and show placeholder if no content
        return text.trim() || placeholder;
    };
}]);
然后,您可以按如下方式使用它:

<th ng-repeat=" o in Odds" >{{o.Name | placeholder:'-'}}</th>
{{o.Name}占位符:'-'}
然后,对于其他行/列以及您希望应用相同规则的任何其他地方,这都是完全可重用的


示例:

创建notapplicate.pipe.ts

@Pipe({name: 'NA'})

export class Notapplicable implements PipeTransform {
  transform(value: string): string {
    let newStr: string = "";
    if(value=='')
    {
        newStr="NA";
    }
    else{
        newStr=value;
    }
    return newStr;
  }
}
包括此应用程序内模块

import { Notapplicable } from './notapplicable.pipe.ts';

declarations: [
    AppComponent,
    Notapplicable
  ],....
并在HTML文件中以这种方式使用它

<tr *ngFor="let article of articledata">
            <td>{{article.a | NA}}</td>
            <td>{{article.b | NA}}</td>
            <td>{{article.c | NA}}</td>
            <td>{{article.d | NA}}</td>
</tr>

{{article.a | NA}}
{{article.b | NA}}
{{article.c | NA}}
{{article.d | NA}}

这样,如果字符串为空,您可以显示NA。如果在规则5中,您可以在ng中使用if-else之类的内容

这样做的好处是,如果您有多条记录要显示: if has记录显示您所拥有的,if has记录不显示“-”。那么您只需要编写一个ng模板

 <td ng-if="o.Name; else showNA">{{ o.Name }}</td>
 <td ng-if="o.Address; else showNA">{{ o.Address }}</td>
 <td ng-if="o.Phone; else showNA">{{ o.Phone }}</td>

<ng-template #showNA>
<td>-</td>
</ng-template>
{{o.Name}
{{o.地址}
{{o.电话}}
-

你的代码是有效的答案提供了一个正确的替代方案,但它们没有说明这样一个事实,即如果你的正确答案不起作用,那么当你运行它时,该值实际上不是错误的。因此,正如前面提到的例子是正确的,你能在
赔率
中发布一个你的数据示例吗?我们可以找出为什么它对你不起作用。随着你的应用程序变得越来越复杂,最好在JS中正确格式化数据并将结果存储在scope中,如果函数返回not string呢?按照上面的代码,您将得到一个错误。说实话,我用一个简单的例子来演示,它直接解决了OP问题。当然,像这样的过滤器为您提供了大量的范围来验证和类型检查您的输入,并将这种计算从HTML文件中去掉。