Question

I'm a newbie to Angular/JS frameworks in general and I'm trying to get this airplane seating data to show up using dynamic templates but its not working.

I tried following the guide at this site but no luck.

Here's my html where 'row.seats' is an object literal and 'row.rowLetter' is a string:

<tr ng-repeat="row in rows">
  <seat-item ng-repeat="seat in row.seats" thisseat="seat" thisrow="row.rowLetter"></seat-item>
</tr>

Here's my directive:

angular.module('myApp.directives', []).directive('seatItem', function($compile) {
  var template1 = '<td> {{thisrow}} {{thisseat.price}} </td>',
      template2 = '<td> seat unavailable </td>';

  var getTemplate = function(thisseat) {
    if(thisseat.isAvailable) {  // is a boolean property on seat object
      return template1;
    }
    return template2;
  }

  var linker = function(scope, element, attrs) {
    element.html(getTemplate(scope.thisseat)).show();
    $compile(element.contents())(scope);  // not sure what contents refers to...
  }

  return {
    restrict: 'E',
    replace: true,
    link: linker,
    scope: {
      thisseat: '=',
      thisrow: '@'
    }
  }
}  

I have a my controller setting $scope.rows but when I tried to move all this logic in a directive (I was originally using ng-ifs in my view) it stopped working. From what I can tell I'm not even getting inside the linker function (although I am entering the directive).

Any help or links to resources would be appreciated!

Était-ce utile?

La solution 2

Okay I was able to fix the problem. 2 main changes to my code:

1) Having a custom tag seemed to confuse the ng-repeated renders so making seat-item an attribute instead fixed the problem.

<tr ng-repeat='row in rows'>
  <td seat-item ng-repeat='seat in row.seats' thisseat='seat' thisrow={{row.row}}>
</tr>

2) The method/attribute .show() and .html were causing errors so instead of:

element.html(getTemplate(scope.thisseat)).show();

changed the code in the linker to:

element.append(getTemplate(scope.thisseat));

Not experienced enough with Angular to know what caused the initial errors but maybe someone in the comments can explain.

Autres conseils

I would use ng-show ng-hide

example:

<tr ng-repeat="row in rows">
    <seat-item ng-repeat="seat in row.seats" thisseat="seat" thisrow="row.rowLetter">
        <td ng-show='seat.isAvailable'> {{thisrow}} {{thisseat.price}} </td>
        <td ng-show='!seat.isAvailable'> seat unavailable </td>
    </seat-item>
</tr>

consult the docs on exactly how show/hide works i may have it backwords but I've used them before and the result worked out great

this will also be more clear to anyone reading your html as to what the template does

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top