我已经处理这个问题有一段时间了。假设我有以下指令和 Controller :
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
};
}
关联 View 如下:
<div class="mainstar"><ratestar></ratestar></div>
<div class='reviews' ng-repeat="review in reviews">
<ratestar class="reviewstars"></ratestar>
</div>
我对链接函数中的范围有疑问。当artistName
更改时,会向数据库发送 GET 请求,然后数据库会使用正确的数据进行响应。我关心的数据被分配给 $scope.ratingInfo
在 promise 回调中。奇怪的是,当我在链接函数中console.log(scope. ratingInfo)仅针对<div class="mainstar"><ratestar></ratestar></div>
时,该数据为12但不适用于<ratestar></ratestar>
位于 ng-repeat
。获取“12”是有意义的,因为这就是我在实例化 Controller 时定义它的方式。理想情况下,我希望以与 <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
});
}
}
};
});
关于javascript - Angular 中的 Link 函数范围未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31012877/