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

时间:2012-09-26 10:26:43

标签: 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>

但是,如果我们使用对象中的参数作为表达式,那么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>

结果

<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有更好理解的人都能帮助我吗?

7 个答案:

答案 0 :(得分:373)

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

答案 1 :(得分:31)

使用角度指令与{{}}绑定时不能使用ng-model但是对于绑定非角度属性,您必须使用{{}} ..

例如:

ng-show="my-model"
title = "{{my-model}}"

答案 2 :(得分:18)

尝试使用:

包装表达式
$scope.$apply(function() {
   $scope.foo.bar=true;
})

答案 3 :(得分:7)

由于我认为ng-show是一个角度属性,我们不需要放置评估花括号({{}})..

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

答案 4 :(得分: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>

答案 5 :(得分:0)

删除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>

答案 6 :(得分:-1)

如果您想根据{{expression}}的状态显示/隐藏元素,可以使用ng-switch

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

foo.bar为true时显示段落,false时显示。