Angular 视图中的条件表达式:如果缺少模型怎么办?

Conditional Expressions in Angular's View: What if a model is missing?

假设我在控制器范围内

$scope.user = {"username": "someUserName"};

正如您在上面看到的,其中没有公司信息。

我想在视图中显示替代文本,如果它丢失了,比如(伪代码):

{{ if "user.company" does not exist show "not set" may be with a certain style }} 

有没有Angular优雅的管理方式?

类似的东西会很棒:

{{ user.company || 'Not set!'.class('danger') }}

在上面的这种情况下,我可以找到 }} 并将其替换为 || 'Not set!'.class('danger') }}

我正在寻找类似的通用解决方案:"Show always a certain text with a certain style, if the corresponding model is missing" ?

假设您必须在具有不同模型值的 100 个不同视图中更正这些值。你能做什么?

您可以使用ng-if/ng-show/ng-hide

像这样

<div ng-if="!user.company">
   Not set
</div>

我认为用表达式处理它更优雅。

Company:  <div>{{user.company || 'Not Set'}}</div>

ng-if / ng-show / ng-hide 应该被使用。

<div ng-if='!user.company'>Company not set</div>
<div ng-if='user.company'>{{user.company}}</div>

<div ng-hide='user.company'>Company not set</div>
<div ng-show='user.company'>{{user.company}}</div>

注:

但是,如果您在特定信息 exists/doesn 不存在的情况下假装更改样式,则可以使用 ng-class。示例:

<div ng-class='{"no-company": !user.company}'>Company not set</div>

比 css 应用您的样式:

.no-company {
    background-color: red;
}

底线:

  • 如果要显示文字,请使用ng-ifng-show/ng-hide
  • 如果您想使用 类 更改样式或应用效果,请使用 ng-class
  • 或者您可以混合使用 angular 指令以获得更复杂的结果。