如何在类型=" text / ng-template"?的页面中使用javascript

时间:2015-08-28 08:55:57

标签: javascript angularjs

我有这样的代码:

<script id="templates/orderdetails.html" type="text/ng-template">

    <ion-view view-title="OrderDetails">

        <ion-content class="padding">

            <p>Here I want to display order details...</p>

            {{ detail }}

<script type="text/javascript">
            var obj = JSON.parse( {{ detail }} );

            document.write('<table>');
            document.write('<thead>');
            document.write('<tr>');
            document.write('<th>菜名</th><th>单价</th><th>份数</th><th>小计</th>');
            document.write('</tr>');
            document.write('</thead>');
            document.write('<tbody>');

            document.write('</tbody>');
            document.write('</table>');

            for(id in obj) {
                document.write(obj[id]["name"]);
                document.write(" ");
                document.write(obj[id]["price"]);
                document.write(" ");
                document.write(obj[id]["num"]);
                document.write(" ");
                document.write(obj[id]["total"]);
                document.write("<br>");
            }
</script>
            <p>
                <a class="button icon ion-home" href="#/tab/home"> Home</a>
            </p>

</ion-content>
</ion-view>

</script>

我希望{{detail}}被解析并显示如下: enter link description here

但我发现javascript无法正常工作&#34; <script id="templates/orderdetails.html" type="text/ng-template">&#34;,我怎么能这样做?感谢。

3 个答案:

答案 0 :(得分:1)

这不会奏效。相反,只需在模板中使用Angular ng-repeat来生成表格。

答案 1 :(得分:1)

您最好将以下table-html添加到模板中,如下所示:

<table>
  <thead>
    <tr>
      <th>菜名</th><th>单价</th><th>份数</th><th>小计</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="id in obj">
       <td>{{name}}</td>
       <td>{{price}}</td>
       <td>{{num}}</td>
       <td>{{total}}</td>
    </tr>
  </tbody>
</table>

Ng-Repeat将为obj变量中的每个项目渲染necesarry表行。之后,您需要在控制器中定义$scope.obj,因为您的角度应用会查找它。我认为只是definig var obj不起作用,但我从未使用过这种方式。

答案 2 :(得分:1)

我假设您正在使用ui-bootstrap-modal(text / ng-template),因此您可以使用{{1}将要使用的对象传递到模式的controller功能。

resolve

在你的模态HTML中,您可以以角度方式简单地使用该对象。

var modalInstance = $modal.open({
            animation: true,
            templateUrl: 'xml-feed.html',
            controller: function($modalInstance,  detail) { 
                this.detail = detail;

                this.close= function () {
                    $modalInstance.close();
                }
            },
            controllerAs: 'myModal',
            size: 'lg',
            resolve: {
                detail: function () {
                    //here you will need to return a reference
                    //I assumed the modal is opened in a controller
                    //that already has the detail object on its scope
                   return $scope.detail;
                }
            }

        });

P.S。我在模态中使用了controllerAs语法。