通过指令插入表

时间:2015-05-30 05:36:26

标签: angularjs

我试图通过Angular1.3中的指令插入一个表 -

控制器

var studentControllerModule = angular.module('studentDetailApp.controllers', []); 
/*StudentController: controller for students*/ 
studentControllerModule.controller('StudentController', function ($scope) { 
$scope.studentList = [ ....];
 });

指令

angular.module('studentDetailApp.directives',[]).directive('studentDirective', function () {
    return {
        template: '<table><thead><tr> <th>NAME</th><th>COUNTRY</th></tr></thead><tbody> <tr ng-repeat="aStudent in studentList"><td>{{aStudent.name }}</td><td>{{aStudent.country }}</td></tr></tbody></table>'};
});

的index.html

    <html lang="en" ng-app="studentDetailApp">
<head>
    <title>AngularJS Partial example</title>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/directives.js"></script>
</head>
<body>
    <div ng-controller="StudentController"> 
    <div studentDirective></div>
    </div>
</body>
</html>

我也不例外 - 但我也没看到桌子。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

你错过了你的ng-app,指令需要在html中规范化: https://docs.angularjs.org/guide/directive 修改后的HTML:

<body ng-app="studentDetailApp">
    <div ng-controller="StudentController"> 
        <div class='a' student-directive></div>
    </div>
</body>

修改JS:

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

app.controller('StudentController', function ($scope) { 
    $scope.studentList = ['nate', 'john', 'seth'];
 });

app.directive('studentDirective', function () {
    return {
        template: '<table><thead><tr> <th>NAME</th><th>COUNTRY</th></tr></thead><tbody> <tr ng-repeat="aStudent in studentList"><td>{{aStudent.name }}</td><td>{{aStudent.country }}</td></tr></tbody></table>'
    };
});

https://jsfiddle.net/cn3otfa6/3/