2015-01-17 67 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; 

    } 
相關問題