AngularJS:ng-show/ng-hide不使用`{{}}`插值

My *_*rts 194 angularjs ng-show ng-hide

我试图使用AngularJS提供的ng-showng-hide函数显示/隐藏一些HTML .

根据文档,这些功能的用途如下:

ngHide - {expression} - 如果表达式为truthy,则元素分别显示或隐藏.ngShow - {expression} - 如果表达式是真实的,那么元素将分别显示或隐藏.

这适用于以下用例:

<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>
Run Code Online (Sandbox Code Playgroud)

但是,如果我们使用来自对象的参数作为表达式,那么ng-hideng-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>
Run Code Online (Sandbox Code Playgroud)

结果

<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>
Run Code Online (Sandbox Code Playgroud)

这可能是一个错误,或者我没有正确地执行此操作.

我找不到关于引用对象参数作为表达式的任何相关信息,所以我希望任何对AngularJS有更好理解的人都可以帮助我吗?

My *_*rts 374

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>
Run Code Online (Sandbox Code Playgroud)

Angular 表达式需要在花括号绑定中,而Angular 指令则不需要.

另请参阅了解角度模板.

  • "Angular表达式需要在花括号绑定中,而Angular指令则不需要." 那条线就在那里.我希望我可以两次投票. (75认同)
  • 如果你想检查该字段是否有值使用:`<p ng-show ="foo.bar ==='test'">我可以显示,或者我可以被隐藏</ p> (3认同)

SHI*_*GHI 31

{{}}使用angular指令进行绑定时不能使用,ng-model但对于绑定非角度属性,则必须使用{{}}..

例如:

ng-show="my-model"
title = "{{my-model}}"
Run Code Online (Sandbox Code Playgroud)


小智 18

尝试用以下方法包装表

$scope.$apply(function() {
   $scope.foo.bar=true;
})
Run Code Online (Sandbox Code Playgroud)

  • `foo.bar = true`应该是`scope.foo.bar = true`,来改变`foo.bar`的值 (7认同)

Raj*_*ian 7

既然ng-show是我想的一个角度属性,我们不需要把评估花括号({{}})..

对于像class我们需要使用评估花括号({{}})封装变量的属性.


Ani*_*ngh 7

<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>
Run Code Online (Sandbox Code Playgroud)