javascript ng-switch 在空字符串上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12434284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-switch on empty string
提问by Timothy Owen
I'm using Angular and I want to check when a string is empty using ng-switch. The following code doesn't seem to be working for me.
我正在使用 Angular,我想使用 ng-switch 检查字符串何时为空。以下代码似乎对我不起作用。
<div ng-switch on="foo">
<span ng-switch-when="">This string is empty</span>
<span ng-switch-default>This string is not empty</span>
</div>
Any help with this would be appreciated.
对此的任何帮助将不胜感激。
采纳答案by Merbs
You will need to include the empty string in your controller:
您需要在控制器中包含空字符串:
function Ctrl($scope) {
$scope.items = ['', 'other'];
$scope.selection = $scope.items[0];
}
For additional reference, see the API: http://docs.angularjs.org/api/ng.directive:ngSwitch
有关其他参考,请参阅 API:http: //docs.angularjs.org/api/ng.directive: ngSwitch
Also, here's a working version of your code: http://jsfiddle.net/upPgU/
此外,这是您的代码的工作版本:http: //jsfiddle.net/upPgU/
回答by christina
<div ng-switch on="foo || 'null'">
<span ng-switch-when="null">This string is empty</span>
<span ng-switch-default>This string is not empty</span>
</div>
回答by Derek Adair
Definite dupe of Angular.js ng-switch ---testing if value is empty or undefined.
Angular.js ng-switch 的绝对欺骗---testing if value is empty 或 undefined。
The accepted answer isn't ideal there either. In my oh so humble opinion the most elegant and clear solution has the least upvotes over there.
那里接受的答案也不理想。在我看来,最优雅、最清晰的解决方案在那里获得的票数最少。
<div ng-switch="!!selection">
<div ng-switch-when="false">Empty, Null or undefined</div>
<div ng-switch-when="true">The string is not empty</div>
</div>