2017-06-19 47 views
0

我对ng-show有个令人沮丧的问题,那就是它不能与功能同步工作,就像它被完全忽略一样。我试图在ng-repeat元素中显示按钮,它基于来自控制器的函数返回true/false。在控制器Angular ng-show与功能不同步

功能代码:

$scope.isRated = function(reservation){ 

      var reservationID = reservation.id; 
      var guestEmail = $rootScope.USER.email; 
      var json = JSON.stringify({ 
       "reservationID": reservationID, 
       "guestEmail": guestEmail.toString(), 
       "venueRating": $scope.foodRating, 
       "restaurantRating":$scope.restaurantRating, 
       "serviceRating":$scope.serviceRating 
      }); 
      var url = "http://localhost:9900/api/reservation/isRated"; 

      $.ajax(
       { 
        type: 'POST', 
        url: url, 
        contentType: "application/json", 
        data : json, 
        success: function (response) { 
         // alert(response + " " + reservationID); 

         return response; 

        }, 
        error: function (err) { 
         console.log(err); 
        } 

       } 

      ); 

HTML格在它应该出现:

<p>{{USER.name}}</p> 
<div class="row" ng-init="loadData()"> 
    <div class="col-md-4"> 
     <label>Passed reservations</label><br/> 
     <div ng-repeat="x in restaurantHistory track by x.id"> 
      {{x.id}} {{x.restaurant.name}} <button ng-show="isRated(x)" ng-click="rateReservation(x)" class="btn btn-link">Rate</button> 
      <hr> 
     </div> 
     <hr> 
     <a href="#advanced">Advanced settings</a> 
     <br/> 
    </div> 

</div> 

功能工作正常,返回布尔通缉,但我不能设法找到一种方法将其与html中的按钮元素进行连接。我尝试了其他问题上的一切,但迄今为止没有运气。没有报告的错误,它只是不工作,因为它应该。

回答

1

isRated是一个异步功能。它产生一个http请求,它不会立即完成,这就是为什么存在回调success的原因。但isRated函数本身立即返回,并且由于它没有返回值,它将返回undefined。所以ng-show看到undefined并从不显示该元素。

每个预订都可以有一个isRated属性。此外,由于ng-show将调用$scope.isRated很多次,你可能需要一个loadingInitiated性质为好,这样可以缓存Ajax响应,并确保你只会使AJAX请求一次:

$scope.isRated = function(reservation) { 
    if (reservation.loadingInitiated) { 
     return reservation.isRated; 
    } 

    reservation.loadingInitiated = true; 

    $.ajax(
    { 
     // ... 
     success: function (response) { 
      reservation.isRated = // ... 
     } 
    } 
    ); 
} 

还要注意的是,你应该使用Angular的$http服务使AJAX调用代替jQuery。通过这种方式,当响应返回时,Angular保证会提取更改并将新值绑定到视图。另外,如果你喜欢,你也可以使用该服务来进行缓存。

+0

非常感谢,解决了我遇到的一个问题! – Lupus

1

问题是您正在使用异步调用。让它工作的一种方法是更新按角度观看的模型,以便视图在更改时更新。

1-用默认值创建一个作用域属性

$scope.isRated = false; 

2-使用新的属性在你的NG-显示

<button ng-show="isRated">Button</button> 

3-更新的属性isRated与Ajax调用