$ http调用后,AngularJS ng-show和ng-hide不会改变状态

时间:2018-05-26 22:24:40

标签: javascript angularjs

我希望在REST AngularJS电话后动态显示$http.get()响应数据。答案很顺利在调用显示{{showOrderStateTrigger}}和预期内容之后插入的数据绑定{{orderDetails}}true仅用于测试目的。但是ng-showng-hide无法识别他们的状况发生了变化。我创建ng-showng-hide个案只是为了测试两种方法。检查变量undefined或布尔变量状态。我尝试了$scope.$apply()电话,但它让事情变得更糟。嵌套调用导致异常。有人可以帮我解决这个问题吗?

        <script type="text/javascript">
            var myApp = angular.module( "myApp", [] );
            myApp.controller( "myController", function( $scope, $http ) 
            { 
              $scope.showOrderDetailsTrigger = false;
              $scope.showOrderDetails = function ( id )
              {
                  $http.get( "/WebApplication1/orders/" + id + ".json" )
                       .then( function ( response ) {
                           $scope.orderDetails = response.data;
                           $scope.showOrderDetailsTrigger = true; } );
              }
            } )
        </script>
    </head>

    <body ng-app="myApp" ng-controller="myController">
        <ul>
            <c:forEach var="order" items="${orders}">
                <li ng-click="showOrderDetails( ${order.id} )">${order.name}</li>
            </c:forEach>
        </ul>

        <div>{{showOrderDetailsTrigger}}</div>
        <div>{{orderDetails}}</div>

        <div ng-show="{{showOrderDetailsTrigger}}">
            <div>ID: {{orderDetails.id}}</div>
            <div>Name: {{orderDetails.name}}</div>
        </div>

        <div ng-hide="{{orderDetails === undefined}}">
            <div>ID: {{orderDetails.id}}</div>
            <div>Name: {{orderDetails.name}}</div>
        </div>

    </body>
</html>

1 个答案:

答案 0 :(得分:1)

许多指令,例如ng-showng-hideng-if期望表达式可以解析真实或虚假而不是插值表达式

尝试更改

ng-show="{{showOrderDetailsTrigger}}"

ng-show="showOrderDetailsTrigger"

对于更高级的条件,例如:

ng-if="somVar != 3 && foo=='bar'"