0

查看角JS指令呼叫与控制器的数据绑定

<star-rating ratingValue="ratings" readonly="true"></star-rating> 
<div><strong>Rating 1:</strong>{{ratings}}</div> 

控制器

app.controller('ProductCtrl', function ($scope, $http, $ionicSlideBoxDelegate, $resource, $state, $stateParams, $rootScope, $compile, $ionicPopup, $location, $sce) { 
     $scope.ratings = 0; 
     this.isReadonly = true; 
     this.rateFunction = function(rating) { 
      console.log('Rating selected: ' + rating); 
     }; 

     $http.defaults.useXDomain = true; 
     $http.get(web_service + 'product/get', { 
      params: {id: $stateParams.ProductId}, 
      headers: {} 
     }).success(function (response) { 
      $scope.product = response.product; 
      console.log(response.product); 
      $ionicSlideBoxDelegate.update(); 
      $scope.ratings = response.product.rating; 
      this.rateFunction = function(rating) { 
       console.log('Rating selected: ' + rating); 
      }; 
     }) 
     .error(function (err) { 
      alert("ERROR"); 
     }); 

    }).directive('starRating', starRating); 

指令

function starRating() { 

    return { 
     restrict: 'EA', 
     template: 
     '<ul class="star-rating" ng-class="{readonly: readonly}">' + 
     ' <li ng-repeat="star in stars" class="star" ng-class="{filled: star.filled}" ng-click="toggle($index)">' + 
     ' <i class="ion-ios-star"></i>' + // or &#9733 
     ' </li>' + 
     '</ul>', 
     scope: { 
     ratingValue: '=?', 
     max: '=?', // optional (default is 5) 
     onRatingSelect: '&?', 
     readonly: '=?' 
     }, 
     link: function(scope, element, attributes) { 
     if (scope.max == undefined) { 
      scope.max = 5; 
     } 
     scope.$observe('ratingValue', function(value){ 
      console.log(value); 
      //$scope.nav.selection = value 
     }); 
     function updateStars() { 
      scope.stars = []; 
      for (var i = 0; i < scope.max; i++) { 
      scope.stars.push({ 
       filled: i < scope.ratingValue 
      }); 
      } 
     }; 
     scope.toggle = function(index) { 
      if (scope.readonly == undefined || scope.readonly === false){ 
      scope.ratingValue = index + 1; 
      scope.onRatingSelect({ 
       rating: index + 1 
      }); 
      } 
     }; 
     scope.$watch('ratingValue', function(oldValue, newValue) { 
      if (newValue) { 
      updateStars(); 
      } 
     }); 
     } 
    }; 
    } 

$ scope.ratings的初始值为1,2,3等数字时,则开始打印,但由ajax请求检索的值未被添加到指令中,并且在指令值中显示“undefined”并且no开始获取打印。

下方查看代码指令的标签使检索到的值指的是这个Codepen:http://codepen.io/TepigMC/pen/FIdHb

我所缺少的指令?

回答

2

使用ng-if以便在$ scope.ratings之后调用该指令。

<star-rating ng-if="ratings" ratingValue="ratings" readonly="true"></star-rating> 
+0

做不工作:( –

+0

Rating 1:{{ratings}}
如果我添加这个然后我得到的收视率 –

+0

值开始工作:)我不知道如何....:d –