Seb*_*rth 54 angularjs angularjs-ng-show
如何检查范围变量是否未定义?
这不起作用:
<p ng-show="foo == undefined">Show this if $scope.foo == undefined</p>
Run Code Online (Sandbox Code Playgroud)
JLe*_*ich 67
这是最干净的方法:
<p ng-show="{{foo === undefined}}">Show this if $scope.foo === undefined</p>
Run Code Online (Sandbox Code Playgroud)
无需在控制器中创建辅助功能!
Umu*_*acı 26
使用undefined
做出决定通常是在Javascript糟糕的设计标志.您可能会考虑做其他事情.
但是,要回答你的问题:我认为这样做的最佳方法是添加帮助函数.
$scope.isUndefined = function (thing) {
return (typeof thing === "undefined");
}
Run Code Online (Sandbox Code Playgroud)
并在模板中
<div ng-show="isUndefined(foo)"></div>
Run Code Online (Sandbox Code Playgroud)
更正:
HTML
<p ng-show="getFooUndef(foo)">Show this if $scope.foo === undefined</p>
Run Code Online (Sandbox Code Playgroud)
JS
$scope.foo = undefined;
$scope.getFooUndef = function(foo){
return ( typeof foo === 'undefined' );
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/oakley349/vtcff0w5/1/
自 Angular 行为发生变化以来,发布新答案。使用 undefined 检查相等性现在可以在角度表达式中使用,至少从 1.5 开始,因为以下代码有效:
ng-if="foo !== undefined"
Run Code Online (Sandbox Code Playgroud)
当这个 ng-if 评估为 true 时,从适当的范围中删除百分比属性并调用 $digest 会从文档中删除该元素,正如您所期望的那样。
归档时间: |
|
查看次数: |
134350 次 |
最近记录: |