zcaudate
zcaudate

Reputation: 14258

how to write custom 'row' and 'col' element for angularjs

I'm trying to write a little dsl around the grid elements outlined here: http://foundation.zurb.com/docs/grid.php

basically what I wish to do is to

<row>
  <column two mobile-one>{{myText}}</col>
  <column four centered mobile-three><input type="text" ng-model="myText"></input></col>
</row>

transform into:

<div class="row">
  <div class="columns two mobile-one">{{myText}}</div>
  <div class= "columns four centered mobile-three"><input type="text" ng-model="myText"></input></div>
</div>

Ideally, I wish to write something that can take arbitrary nesting: row -> col -> row -> col -> row.....

I am having trouble getting the first step right - nesting the elements because I can't quite figure how how to get the child elements into another template without seriously compromising the compilation process.

  var app = angular.module('lapis', []);

  app.directive('row', function(){
    return {
      restrict: 'E',
      compile: function(tElement, attrs) {
        var content = tElement.children();
        tElement.replaceWith(
          $('', {class: 'row',}).append(content));
      }
    }
  });

just does not do anything. The failed attempt is shown here - http://jsfiddle.net/ZVuRQ/

Please help!

Upvotes: 3

Views: 6002

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364677

I was hoping not to use ng-transclude because I found that it added an additional scope.

Here is a directive that does not use ng-transclude:

app.directive('row', function() {
    return {
        restrict: 'E',
        compile: function(tElement, attrs) {
            var content = angular.element('<div class="row"></div>')
            content.append(tElement.children());
            tElement.replaceWith(content);
        }
    }
});

You may want to use tElement.contents() instead of tElement.children().

Upvotes: 7

asgoth
asgoth

Reputation: 35829

You don't need jquery at all in your example (but you need to include it on your page/jsFiddle):

var app = angular.module('lapis', []);


app.directive('row', function(){
    return {
      restrict: 'E',
      template: '<div class="row" ng-transclude></div>',
      transclude: true,
      replace: true
    };
});   

Upvotes: 1

Related Questions