2014-01-05 31 views
0

以下是我的指令代码:测试表指示问题

currentApp.directive('testList', ['$compile', function ($compile) { 

    return{ 
     restrict: 'E', 
     template: '<table></table>', 
     replace: true, 
     compile: function (elem) { 
      return function ($scope, elem) { 
       var arr = ['Jay', 'John', 'David']; 
       angular.forEach(arr, function (val) { 
        elem.append('<tr><td>' + val + '</td></tr>'); 


       }); 
       $compile(elem)($scope); 
      } 

     } 

    } 

}]); 

,这是我的测试代码:

describe('Tabletest', function() { 

    var element, scope, elem; 
    var linkingFn; 
    beforeEach(module('angularlearnApp')); 

    beforeEach(inject(function ($compile, $rootScope) { 
     scope = $rootScope; 
     elem = angular.element('<test-list></test-list> '); 
     linkingFn = $compile(elem); 
     element = linkingFn(scope); 
    })); 

    it('Testing table', function() { 

     console.info(element); 
    }); 
}); 

这是测试的输出:

Object{0: <table class="ng-scope">JayJohnDavid</table>, 1: , length: 2} 

我我只是想知道为什么tr和td标签没有出现在这里,只有值出现。

+0

没有真正回答您的具体问题,但你应该利用NG重复指令。例如... http://jsfiddle.net/HB7LU/1511/ –

+0

你能为此创建一个jsfiddle吗? – dcodesmith

+0

我然而,在它出现这样的测试与NG-重复的方法试过:< - ngRepeat:在ARR值 - > – Asutosh

回答

0

您需要.html()而不是.append(),因为tr是表格内容,您不会将它们追加到表格末尾。 ;)

此外,您需要在将循环中的表格行传递到表格中之前建立表格行,如果不是索引中的最新项目/名称将继续取代之前的表格,并且最终会生成一个表格只有一个以“David”作为内容的表格行。

currentApp.directive('testList', ['$compile', function ($compile) { 

    return { 
     restrict: 'E', 
     template: '<table/>', 
     replace: true, 
     link: function ($scope, elem) { 
      var arr = ['Jay', 'John', 'David'], trHTML =''; 
      angular.forEach(arr, function (val) { 
       trHTML += '<tr><td>' + val + '</td></tr>'; 
      }); 
      angular.element(elem).html(trHTML); 
      $compile(elem)($scope); 
     } 
    } 
}]); 

JSFIDDLE

+0

谢谢,它的工作 – Asutosh

+0

你”欢迎;) – dcodesmith

+0

@Asutosh,出于好奇,你在桌上测试什么?我试图测试它是否包含一个特定的类,但我似乎无法看出它返回一个对象,如你在你的问题中显示的那样。 – dcodesmith