【问题标题】:Whats wrong with my code我的代码有什么问题
【发布时间】:2015-09-13 15:07:17
【问题描述】:

我希望将 tableRow.html 绘制在表头下方,但 ng-repeat 根本不绘制,示例位于表头上方。如果我将带有示例的行直接放到 index.html 中的正确位置,它会画得很好。我究竟做错了什么? index.html

<html>
<head>
    <title>Currency Exchange</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="css/stylesheet.css"/>
    <script type="text/javascript" src="js/angular.min.js"></script>

</head>
<body ng-app="myApp">
    <h1>A title to the table</h1>
    <div>
        <div class= "ExTableDiv">
            <table class= "ExTable">
            <thead>
                <tr>
                    <th class="column">Currency Code</th>
                    <th class="column">Currency Name</th>
                    <th class="column">Exchange Rate vs USD</th>
                </tr>
            </thead>
            <tbody ng-controller="TestController"><!--**if you try TestController as TC it will throw an error, why?**-->
                <test-directive></test-directive>
            </tbody>
            </table>
        </div>
    </div>
</body>
    <script type="text/javascript" src="js/app.js"></script>
    <script type="text/javascript" src="js/directives/tableFiller.js"></script>
</html>

app.js

(function(){
var app = angular.module('myApp',['exchange-directives']);

app.controller('TestController', ['$http', function($http) {
var table = this;
table.rows = [];
$http.get('/item.json').success(function(data){
    table.rows = [{"name":"Captain","rate":"0.8910","inverce":"1.1223"}]; //I added this here so I know I am getting json data
});
}]);
})();

tableFiller.js

(function(){
var app = angular.module('exchange-directives', []);

app.directive('testDirective', function(){
    return {
        restrict: 'E',
        templateUrl: 'js/directives/tableRow.html'
    };
});
})();

tableRow.html

<tr ng-repeat='row in TestController.table.rows'>
<td>{{row.name}}</td>
<td>{{row.rate}}</td>
<td>{{row.inverse}}</td>
</tr>
<tr>
    <td>Example 1</td>
    <td>Example 2</td>
    <td>Example 3</td>
</tr>

【问题讨论】:

  • 您能否编辑您的问题以同时提出一件事 - 您想知道为什么您的代码不起作用,还是其他问题的答案?
  • 让我们先来看看为什么表不工作,问题已编辑

标签: javascript html angularjs


【解决方案1】:

&lt;tr ng-repeat='row in TestController.table.rows'&gt; 替换为 &lt;tr ng-repeat='row in TestController.rows'&gt;

在您的控制器中,您正在设置table = this,因此table.rows 实际上是this.rows,因此可通过TestController.rows 进行标记

【讨论】:

  • 我照你说的做了,但没有任何改变
【解决方案2】:

我选择回答这个问题:

我在 codeschool 上遵循的教程也将 angular.module 包装在一个函数中,但我发现大多数其他示例都没有。有什么不同?为什么选择一个而不是另一个?

这称为immediately invoked function expression 或 (IIFE)。这是一种将模块引入 JavaScript 的轻量级方法。使用这样的东西的目的是确保在模块顶层声明的所有变量的词法范围。如果没有这样的东西,很容易不小心引入全局变量,这通常是一件很糟糕的事情。

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2019-06-06
    • 1970-01-01
    • 2010-11-08
    • 2016-01-31
    相关资源
    最近更新 更多