2013-01-11 46 views
0

我一直在使用句柄到現在爲JavaScript模板。但是我想使用angularJs。我想知道是否有人可以提出一個轉換到angularjs的好方法。例如,如果我有一個模式。我創建一個句柄模板,將其包含在我的頁面底部,然後獲取一個js func(rest api)中的數據,並告訴句柄模板將編譯成一個div等。把手到angularjs

這裏是一個例子js函數使用句柄以模態顯示事物。

$('[data-toggle="tabularmodal"]').click(function(e) 
{ 
    e.preventDefault(); 
    var data_uri = $(this).attr('data-uri'); 
    var data_title = $(this).attr('data-header'); 
    var data; 
    var source = $('#tabular-ep-data').html(); 
    var template = Handlebars.compile(source); 
    $('.modal-header h3').html(data_title); 
    $.getJSON(data_uri, function(json) 
    { 
     $('.modal-body').html(template(json)); 
    }); 
    $('#myModal').modal('show'); 
}); 

我想就如何以angularjs方式實現這一點提出一些建議。在句柄中,我必須在頁面的底部包含javascript模板等等,而我想要遠離這一點。

+0

你瞭解的指令? – mpm

回答

9

在Angular中,您將創建一個directive,例如, modal,這簡直可以放在任何標記,如:正如你所看到

<button modal="path/to/partial">Open modal</div> 

甚至

<modal template-url="path/to/partial">Open modal</modal> 

,它是非常靈活的。需要一些時間來深入理解指令,但一旦你做了,它們就非常強大。對於你想操作DOM的所有東西,指令就是答案。

在指令中,您可以注入服務,這可以使生活更輕鬆。例如,$http可以用於通過異步請求獲得部分。另一個有用的服務是$compile,它準備模板,所以它可以插入到DOM中。

下面是一個例子的modal指令能看怎麼樣(但可能性幾乎是無止境):

var app = angular.module('app', []); 
app.directive('modal', ['$http', '$compile', function($http, $compile) { 
    return { 
     restrict: 'E', 
     link: function(scope, elm, attrs) { 
     element.on('click', function(e) { 
      $http.get(attrs.templateUrl).success(function(template) { 
       var html = $compile(template)(scope); 

       // insert html somewhere 
       scope.$apply(); 
      }); 
     }); 

     } 
    }; 
}]);