首页 > 解决方案 > 范围变量在angularjs的html模板中不起作用

问题描述

我正在尝试将variation variablefrom传递card.htmltooltip.htmlangulajs。但是,无论出于何种原因,它都不起作用。当我console.log(scope.variation)进去的时候interestRateTooltip.directive.js,它正在向我展示apr

另外,tooltip.html如果我有以下

<div>
  {{ variation }}
</div>

它显示apr在一个 div 中。所以我不明白为什么<i tooltip position="{{ variation === 'apr' ? 'left' : 'right'}}">总是会是假的,变成right.

从今天早上开始,我已经花了 6 个小时搜索。有人可以帮忙吗?谢谢!

card.html

<div>
  <interest-rate-tooltip variation="apr"></interest-rate-tooltip>
</div>

interestRateTooltip.directive.js

angular.module("borrower.offers").directive('interestRateTooltip',  function () {
  return {
    restrict: "E",
    templateUrl: ".../card.html",
    link: function(scope, element, attrs) {
      if (attrs.variation === 'apr') {
        scope.variation = 'apr';
      }
    }
  }
});

tooltip.html

<div>
  <i tooltip position="{{ variation === 'apr' ? 'left' : 'right'}}">
</div>

tooltip.directive.js

angular.module("borrower.offers")
  .directive("tooltip", function() {
    return {
      restrict: "A",
      link: function(scope, element, attrs) {

        var params = {};

        switch (attrs.position) {
          case 'left':
            params = { position: 'bottom left' }
            break;
          case 'right':
            params = { position: 'bottom right' }
            break;
          case 'center':
            params = { position: 'bottom center' }
            break;
        }
      }
    }
  });

标签: angularjs

解决方案


您的问题可能是因为您正在访问attrs.position指令的内部链接函数。由于链接功能仅触发一次,因此在触发时,您的attrs.positionis可能是未定义的。您可以将 添加到指令中并将链接函数的内容包装在其中,从而强制进行摘要。rightvariation$timeout

它会是这样的:

.directive("tooltip", ['$timeout', function($timeout) {
return {
  restrict: "A",
  link: function(scope, element, attrs) {

    $timeout(function() {
        var params = {};

      switch (attrs.position) {
        case 'left':
          params = { position: 'bottom left' }
          break;
        case 'right':
          params = { position: 'bottom right' }
          break;
        case 'center':
          params = { position: 'bottom center' }
          break;
      }
    });
   }
  }
}]);

这可能会解决您的问题,但也有人可能会想到更好的解决方案。


推荐阅读