سؤال

I really struggle on how to do templating in angular. So I have a table, I'm populating it like this:

 <tr ng-repeat="store in stores">
    <td>
       <p>{{store.day_one.visitor_count}}</p>
       <span>ng-class="{green: ... >= 0, red: ... < 0}"</span>
       <small>store.difference.visitor_count</small>
    </td>
    <td>
       <p>{{store.day_one.conversion_rate}}</p>
       ...
    </td>
    <td>
       ...
       <p>{{store.day_one.dwell_time}}</p>
       ...
    </td>
 </tr>

But i really would like to have, something more like:

<td reportNumber="{numberOne: store.day_one.visitor_count,
                   numberTwo: store.difference.visitor_count}>
</td>

Option 1:

Write a directive, that creates the appriopriate html and append it to td... but how to write html-strings in directives? I couldn't find a util method in angular that allows me to write html-strings in a nice way and writing it like '<p>' + 'numberOne' + </p>... is a pain.

But there are also partials, couldn't I just use partials and populate them in the directive? I wasn't able to find a proper way to load them and fetching them via $http seems strange.

Option 2:

Use ng-include directly, but how to create scope variables in the view in a appropriate way?. I could to something like:

<td dummyVar="{{ numberOne = store.day_one.visitor_count;
                 numberTwo = store.difference.visitor_count}}"
  ng-include="'/static/angular/views/partials/reportNumber.html'">
</td>

But this seems rather hacky than clean and I don't know if there could be problems with redefining these variables all the time.

My Question: How to create the table in a nice way using templates?

هل كانت مفيدة؟

المحلول

Use a directive as simple as:

app.directive("mytd", function() {
    return {
        template:
            "<div>" +
                "<p>{{num}}</p>" +
                "<span ng-class='{green: diff >= 0, red: diff < 0}'></span>" +
                "<small>{{diff}}</small>" +
            "</div>",
        scope: {
            num: "=",
            diff: "="
        }
    };
});

And use it like:

<td mytd="" num="store.day_one.visitor_count" diff="store.difference.visitor_count"></td>

See fiddle: http://jsfiddle.net/ztxTe/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top