我正在尝试使用 AngularJS 提供的 ng-show
和 ng-hide
函数显示/隐藏一些 HTML。
根据文档,这些功能的各自用法如下:
ngHide - {表达式} - 如果表达式为真,则分别显示或隐藏元素。 ngShow - {表达式} - 如果表达式为真,则元素分别显示或隐藏。
这适用于以下用例:
<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>
但是,如果我们使用来自对象的参数作为表达式,那么 ng-hide
和 ng-show
将被赋予正确的 true
/false
值,但这些值不会被视为布尔值,因此始终返回 false
:
资源
<p ng-hide="{{foo.bar}}">I could be shown, or I could be hidden</p>
<p ng-show="{{foo.bar}}">I could be shown, or I could be hidden</p>
结果
<p ng-hide="true">I should be hidden but I'm actually shown</p>
<p ng-show="true">I should be shown but I'm actually hidden</p>
这要么是一个错误,要么是我没有正确执行此操作。
我找不到任何关于将对象参数引用为表达式的相关信息,所以我希望任何对 AngularJS 有更好理解的人都可以帮助我?
foo.bar
引用不应包含大括号:
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
Angular expressions 需要在花括号绑定中,而 Angular directives 不需要。
另见Understanding Angular Templates。
使用角度指令与 ng-model
绑定时不能使用 {{}}
,但要绑定非角度属性,则必须使用 {{}}
..
例如:
ng-show="my-model"
title = "{{my-model}}"
尝试用以下方式包装表达式:
$scope.$apply(function() {
$scope.foo.bar=true;
})
foo.bar = true
应为 scope.foo.bar = true
,以更改 foo.bar
的值
$scope.$apply
由于我认为 ng-show
是一个角度属性,我们不需要将评估花括号 ({{}}
)..
对于像 class
这样的属性,我们需要用评估花括号 ({{}}
) 封装变量。
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script type="text/javascript">
function controller($scope) {
$scope.data = {
show: true,
hide: false
};
}
</script>
<div ng-controller="controller">
<div ng-show="data.show"> If true the show otherwise hide. </div>
<div ng-hide="!(data.hide)"> If true the show otherwise hide.</div>
</div>
删除 foo.bar 周围的 {{}} 大括号,因为角度表达式不能在角度指令中使用。
更多:https://docs.angularjs.org/api/ng/directive/ngShow
例子
<body ng-app="changeExample">
<div ng-controller="ExampleController">
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
</div>
</body>
<script>
angular.module('changeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.foo ={};
$scope.foo.bar = true;
}]);
</script>
如果要根据一个 {{expression}} 的状态显示/隐藏元素,可以使用 ng-switch
:
<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>
当 foo.bar 为 true 时,该段落将显示,为 false 时隐藏。
不定期副业成功案例分享
<p ng-show="foo.bar === 'test'">I could be shown, or I could be hidden</p>