我已经处理了一段时间了。假设我有以下指令和控制器:
angular.module('LiveAPP.artist',[])
.controller('artistCtrl', ['$scope', '$http', '$location', 'dataFactory', '$routeParams', artistCtrl])
.directive("ratestar", function() {
return {
restrict: "E",
template: "<div id='rateYo'></div>",
link: function( scope, ele, attrs ) {
console.log(scope.ratingInfo)
if(scope.reviews === undefined){
$rateYoMain = $(ele).rateYo({
rating:3
})
} else {
var $rateYo = $(ele).rateYo({
starWidth: "20px",
rating:scope.review.number_of_stars
});
}
}
};
})
function artistCtrl($scope, $http, $location, dataFactory, $routeParams){
$scope.artistName = $routeParams.artistname;
$scope.$watch( 'artistName', function( newValue, oldValue ) {
dataFactory.checkDb( newValue ).then(function(dbData){
if(dbData.data != "No data"){
$scope.artistInfo = dbData.data[0];
$scope.reviews = dbData.data[1];
$scope.ratingInfo = dataFactory.avgReview($scope.reviews);
} else{
dataFactory.artistInfoAPIs(newValue);
}
})
});
$scope.$on('artist:updated', function(event, data){
$scope.artistInfo = data;
});
$scope.ratingInfo = "12";
$scope.artistInfo = {
artist_name: dataFactory.artistInfo.artist_name,
artist_genre: dataFactory.artistInfo.artist_genre,
artist_imageurl: dataFactory.artistInfo.artist_imageurl,
artist_bio: dataFactory.artistInfo.artist_bio
};
}
关联的视图如下:
<div class="mainstar"><ratestar></ratestar></div>
<div class='reviews' ng-repeat="review in reviews">
<ratestar class="reviewstars"></ratestar>
</div>
我在链接功能的范围上有问题。当
artistName
更改时,将有一个GET请求发送到数据库,然后以正确的数据进行响应。我关心的数据是在promise回调中分配给$scope.ratingInfo
的数据。奇怪的是,当我在link函数中的console.log(scope.ratingInfo)仅用于<div class="mainstar"><ratestar></ratestar></div>
而不是<ratestar></ratestar>
中的ng-repeat
时,此数据为12。获得“ 12”很有意义,因为这是我在实例化控制器时定义它的方式。理想情况下,我希望以与查看<ratestar></ratestar>
中的ng-repeat
相同的方式查看数据。我似乎无法弄清楚。有人知道这是怎么回事吗? 最佳答案
你可以试试这个吗?
<div class="mainstar"><ratestar ratingInfo="ratingInfo" review="review"></ratestar></div>
<div class='reviews' ng-repeat="review in reviews">
<ratestar class="reviewstars" ratingInfo="ratingInfo" review="review"></ratestar>
</div>
.directive("ratestar", function() {
return {
restrict: "E",
template: "<div id='rateYo'></div>",
scope: {
ratingInfo : '=ratingInfo',
review: '=review'
},
link: function( scope, ele, attrs ) {
console.log(scope.ratingInfo)
if(scope.reviews === undefined){
$rateYoMain = $(ele).rateYo({
rating:3
})
} else {
var $rateYo = $(ele).rateYo({
starWidth: "20px",
rating:scope.review.number_of_stars
});
}
}
};
});