2015-01-17 143 views
1

在我的指令:如何从指令数据传递给HTML模板 - AngularJS

angular.module('myPopUp',[]) 
.directive('myPopUp',['$document', function($document){ 

    return{ 
     restrict: 'EA', 
     controller: function($scope){ 
     }, 
     scope: { 

     }, 
     templateUrl: 'popup.html', 
     link: function(scope, elm, attr){ 
     var topPosition = top + (btnHeight/2) - (popOverHeight/2); 

     } 

在做链接的计算后,如何可以通过“topPosition”我popup.html模板?有任何想法吗?

我尝试这样做,但它不起作用。

popup.html:

<div class="popover right" style="width:auto;top:{{topPosition}}px;"> 
     <div class="arrow"></div> 
     <div>.......</div> 
    </div> 

回答

1

问题解决了。我添加了$适用于我的代码:

link: function(scope, elm, attr) { 
var topPosition = top + (btnHeight/2) - (popOverHeight/2); 
scope.$apply(function() { 
    scope.topPosition = topPosition; 
    } 
} 
2

您可以变量分配你scope,就像链接位指示和范围本

link: function(scope, elm, attr) { 
    var topPosition = top + (btnHeight/2) - (popOverHeight/2); 
    scope.topPosition = topPosition; 
} 
0

$范围是一样的。唯一不同的是$范围是通过依赖注入注入的,而link fxn范围是基于位置注入的。因此对于例如

link: function(element, scope, attr) 

然后element仍然会引用范围。

所以在你的link函数中,你可以将position分配给作用域,就像你将它分配给控制器一样,差别就是变量名。例如。

.directive('myPopUp', function(){ 

     return{ 
      restrict: 'EA', 
      controller: function($scope){ 
       $scope.topPosition = 0; 
      }, 
      scope: { 

      }, 
      templateUrl: 'popup.html', 

      link: function(scope, elm, attr){ 
       scope.topPosition = 200; // calculate here as per your logic 
      }}}); 

demo

+0

感谢您的回答,但它仍然无法正常工作。我错过了什么?我曾尝试添加 范围:topPosition:'@' }, 但仍不能正常工作....任何想法? – user2991183

+0

@ user2991183更新并附带演示链接 – sol4me

0

可以仅指范围内的变量在你的模板让你的范围应该有topPosition。

link: function(scope, elm, attr){ 
      var topPosition = top + (btnHeight/2) - (popOverHeight/2); 
      scope.topPosition = topPosition; 

    } 
相关问题