所以我知道在SO上有关于这个问题的各种问题。我检查了它们的负载并尝试了各种组合,但仍然无法获得我的指令来渲染。
基本上我试图在ng-repeat中将一个整数传递给我的指令,并让它根据数字渲染一个表情符号。
问题是scope.userpoints变量在模板中是未定义的,但在链接函数中没有定义...
这是html。请注意,$scope.favourites
和f av.update
都是异步填充的
<div ng-repeat="fav in favourites">
<dencity-rank userpoints="fav.update.poster.points"></dencity-rank>
</div>
这是指令代码
.directive('dencityRank', [function(){
Number.prototype.between = function (min, max) {
return this >= min && this <= max;
};
var getEmojiRank = function(points){
console.log(points);
if(typeof(points) === "undefined") return;
if (points < 3) return "em-hatched_chick";
else if (points.between(4, 8)) return "em-hatched_chick";
else if (points.between(9, 14)) return "em-baby_chick";
else return "em-hatched_chick";
};
return {
scope: {
userpoints: '=',
}, // use a new isolated scope that does not inherit from parent
restrict: "E", // use as html element
replace: false, // replace the directive with the result of the directive?
template: function(scope){
return '<i class= "em ' + getEmojiRank(scope.userpoints) + ' emoji-align"></i>'; // this doesnt work
},
link: function (scope, element, attrs) {
//console.log(getEmojiRank(scope.userpoints)); // this works
}
};
}]);
答案 0 :(得分:1)
好吧,这里有很多问题...... 首先,您必须在指令范围内定义函数,然后在模板中调用它(示例代码,未经测试):
angular.module('yourApp', []).directive('dencityRank', function(){
return {
restrict: 'E',
scope: {userpoints: '='},
controller: ['$scope', function($scope) {
$scope.getEmojiRank = function(points){
// If you like you can use $scope.userpoints directly and omit the function parameter
//...
};
}],
template: '<i class= "em {{ getEmojiRank(userpoints) }} emoji-align"></i>'
};
});
// Move somewhere into global scope to make this definition only once
Number.prototype.between = function (min, max) {
return this >= min && this <= max;
};