viperfx
viperfx

Reputation: 327

Handlebars to angularjs

I have been using handlebars up to now for javascript templates. However I want to use angularJs. I was wondering if someone could suggest a good way to transition to angularjs. For example if I have a modal. I create a handlebars template, include it at the bottom of my page, then get the data in a js func (rest api) and tell the handlebars template to put the compiled in a div etc.

Here is an example js function that uses handlebars to show things in a modal.

$('[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');
});

I would like some suggestions on ways to achieve this in angularjs ways. In handlebars I have to include javascript templates at the bottom of my page etc.. and I want to move away from that.

Upvotes: 0

Views: 3517

Answers (1)

asgoth
asgoth

Reputation: 35829

In Angular you would make a directive, e.g. modal, which simply can be placed on any tag like:

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

or even

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

As you see, it is very flexible. It takes some time to deeply understand directives, but once you do, they are very powerful. For everything you want to manipulate the DOM, directives are the answer.

In a directive, you can inject services, which can make life easier. E.g., $http can be used to get the partial via an async request. Another useful service is $compile, which prepares the template, so it can be inserted in the DOM.

Here is an example how a modal directive could look like (but possibilities are almost endless):

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();
            });
         });

      }
   };
}]); 

Upvotes: 9

Related Questions