2014-04-14 88 views
6

我已經開始了一個angularjs項目,並且我想實現fancybox。AngularJS Fancybox Popup

爲此,我將jQuery和fancybox插件包含到解決方案中。我試圖在fancybox窗口中的下面顯示的代碼中打開模板。

查看

<a href="" ng-click="openPage('popups/add.html')">ADD</a>

控制器

app.controller('MainController', 
    function MainController($scope) { 
     $scope.user = "Hey Welcome"; 

     $scope.open = function(template_path){ 
      $.fancybox({"href":template_path}) 
     } 
    } 
) 

而且彈出/ add.html

<div class="pop-contnr"> 
    <h2>ADD</h2> 
    <table> 
     <thead> 
      <tr> 
       <th align=center>{{user}}</th> 
      </tr> 
     </thead> 
    </table> 
</div> 

Fancybox成功打開一個包含模板的窗口,但尚未評估{{user}}表達式。任何人都可以幫忙嗎?

回答

8

我創建了一個指令,爲的fancybox

app.directive('fancybox',function($compile, $timeout){ 
    return { 
     link: function($scope, element, attrs) { 
      element.fancybox({ 
       hideOnOverlayClick:false, 
       hideOnContentClick:false, 
       enableEscapeButton:false, 
       showNavArrows:false, 
       onComplete: function(){ 
        $timeout(function(){ 
         $compile($("#fancybox-content"))($scope); 
         $scope.$apply(); 
         $.fancybox.resize(); 
        }) 
       } 
      }); 
     } 
    } 
}); 
8

這裏是一個的fancybox指導我的團隊的簡化版本,我寫信給打開基於一個單一的點擊模板fancyboxes。

會調用它在類似這樣的標記:

<div fancybox ng-click="openFancybox('templateUrl')"> </div> 

的指令的代碼是:

app.directive('fancybox', function ($compile, $http) { 
    return { 
     restrict: 'A', 

     controller: function($scope) { 
      $scope.openFancybox = function (url) { 

       $http.get(url).then(function(response) { 
        if (response.status == 200) { 

         var template = angular.element(response.data); 
         var compiledTemplate = $compile(template); 
         compiledTemplate($scope); 

         $.fancybox.open({ content: template, type: 'html' }); 
        } 
       }); 
      }; 
     } 
    }; 
}); 

可以看出在這個plunker

+0

我不想在每次單擊元素時加載模板 - 是否有任何可加載的模板只能加載一次? – Tony

+0

好東西,非常感謝!看起來像Angular的內部模板加載器(在指令中)有問題在初始化時被fancybox識別出來......這種方法保證模板真的存在。 – Alex

+0

@Tony - 瀏覽器將緩存模板,因此將保存HTTP往返。 – Alex

0

工作,我延長了answer above使用Angular的模板緩存。

它是在標記調用是這樣的:

<div fancybox fancybox-template="template.html">Open Fancybox</div> 

的指令的代碼是:

app.directive('fancybox', function ($templateRequest, $compile) { 
    return { 
     scope: true, 
     restrict: 'A', 
     controller: function($scope) { 
      $scope.openFancybox = function (url) { 
       $templateRequest(url).then(function(html){ 
        var template = $compile(html)($scope); 
        $.fancybox.open({ content: template, type: 'html' }); 
       }); 
      }; 
     }, 
     link: function link(scope, elem, attrs) { 
      elem.bind('click', function() { 
       var url = attrs.fancyboxTemplate; 
       scope.openFancybox(url); 
      }); 
     }, 
    } 
}); 

這裏的plunker