$scope 变量在指令隔离范围内未定义

$scope variable is undefined in directive isolated scope

所以我知道在 SO 上有很多关于这个问题的问题。我已经检查了它们的负载并尝试了各种组合,但我仍然无法让我的指令呈现。

本质上,我试图在 ng-repeat 中将一个整数传递给我的指令,并让它根据该数字呈现表情符号。

问题是 scope.userpoints 变量在模板中未定义,但在 link 函数中未定义...

这是html。请注意,$scope.favourites 和 fav.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;
};