Поэтому я знаю, что есть разные вопросы по этому вопросу на SO. Я проверил грузы из них и пробовал различные комбинации, и я все еще не могу получить свою директиву для рендеринга.
По сути, я пытаюсь передать целое число в мою директиву в ng-repeat и заставить его отображать emoji на основе числа.
Проблема в том, что переменная 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
}
};
}]);
Хорошо, здесь много проблем... Сначала вам нужно определить функцию в области действия директивы, а затем вызвать ее в своем шаблоне (пример кода, не протестирован):
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;
};