use*_*779 190 if-statement ternary-operator angularjs
我想知道是否有一种角度有条件地显示内容而不是使用ng-show等.例如在backbone.js我可以在模板中使用内联内容做一些事情,如:
<% if (myVar === "two") { %> show this<% } %>
Run Code Online (Sandbox Code Playgroud)
但在角度方面,我似乎仅限于显示和隐藏包含在html标签中的内容
<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>
Run Code Online (Sandbox Code Playgroud)
如果使用{{}}而不是将内容包装在html标记中,有条件地以角度显示和隐藏内嵌内容的角度建议方法是什么?
2To*_*oad 717
Angular 1.1.5增加了对三元运算符的支持:
{{myVar === "two" ? "it's true" : "it's false"}}
Run Code Online (Sandbox Code Playgroud)
Ben*_*esh 138
还有一个答案.我发布了一个单独的答案,因为它更像是对解决方案的"精确"尝试,而不是可能的解决方案列表:
这是一个过滤器,它将执行"立即if"(aka iif):
app.filter('iif', function () {
return function(input, trueValue, falseValue) {
return input ? trueValue : falseValue;
};
});
Run Code Online (Sandbox Code Playgroud)
并可以像这样使用:
{{foo == "bar" | iif : "it's true" : "no, it's not"}}
Run Code Online (Sandbox Code Playgroud)
Ben*_*esh 60
成千上万的皮肤养猫方法.我意识到你要特别在{{}}之间询问,但是对于其他来到这里的人,我认为值得展示一些其他选择.
在$ scope上运行(IMO,在大多数情况下这是你最好的选择):
app.controller('MyCtrl', function($scope) {
$scope.foo = 1;
$scope.showSomething = function(input) {
return input == 1 ? 'Foo' : 'Bar';
};
});
<span>{{showSomething(foo)}}</span>
Run Code Online (Sandbox Code Playgroud)
ng-show和ng-hide当然:
<span ng-show="foo == 1">Foo</span><span ng-hide="foo == 1">Bar</span>
Run Code Online (Sandbox Code Playgroud)
<div ng-switch on="foo">
<span ng-switch-when="1">Foo</span>
<span ng-switch-when="2">Bar</span>
<span ng-switch-default>What?</span>
</div>
Run Code Online (Sandbox Code Playgroud)
Bertrand建议使用自定义过滤器.(如果你不得不一遍又一遍地做同样的事情,这是你最好的选择)
app.filter('myFilter', function() {
return function(input) {
return input == 1 ? 'Foo' : 'Bar';
}
}
{{foo | myFilter}}
Run Code Online (Sandbox Code Playgroud)
或者自定义指令:
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.$watch(attrs.value, function(v) {
elem.text(v == 1 ? 'Foo': 'Bar');
});
}
};
});
<my-directive value="foo"></my-directive>
Run Code Online (Sandbox Code Playgroud)
就个人而言,在大多数情况下,我会使用我的示波器上的函数,它使标记非常干净,并且实现起来快速而简单.除非,也就是说,你要一遍又一遍地做同样的事情,在这种情况下,我会考虑Bertrand的建议并创建一个过滤器或可能的指令,具体取决于具体情况.
与往常一样,最重要的是您的解决方案易于维护,并且有望可测试.这完全取决于您的具体情况.
Ash*_*vis 18
当使用ng-class时,我使用以下条件有条件地设置类attr(例如在设置SVG样式时):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
Run Code Online (Sandbox Code Playgroud)
相同的方法应该适用于其他属性类型.
(我认为你需要使用最新的不稳定Angular来使用ng-attr-,我目前正在使用1.1.4)
我发表了一篇关于使用AngularJS + SVG的文章,讨论了这个问题和相关问题.http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
eze*_*elc 15
要检查变量内容并使用默认文本,您可以使用:
<span>{{myVar || 'Text'}}</span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
284213 次 |
| 最近记录: |