What are the best practices for incorporating Javascript into a page with the type "text/ng-template"?

I am currently working with the following code:

<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>

I would like the content of {{ detail }} to be parsed and displayed as shown in this image: enter link description here

However, I have encountered an issue where JavaScript is not functioning within "

<script id="templates/orderdetails.html" type="text/ng-template">
". How can I resolve this? Thank you.

Answer №1

To enhance your template, consider incorporating the following HTML table:

<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 dynamically generates table rows for each item within the obj variable. Remember to define $scope.obj in your controller as necessary for proper functionality. Simply declaring var obj may not suffice, based on my experience.

Answer №2

Trying this method will be ineffective. It would be better to utilize Angular's ng-repeat within the template in order to create your table.

Answer №3

If you are utilizing the ui-bootstrap-modal (text/ng-template), then you have the ability to pass the desired object into the controller of your modal by utilizing the resolve feature.

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;
                }
            }

        });

You can easily utilize the passed object in an angular way within your modal's HTML.

<table>
  <thead>
    <tr>
      <th>菜名</th><th>单价</th><th>份数</th><th>小计</th>
    </tr>
  </thead>
  <tbody>
        <tr><td>{{myModal.detail}}</td><tr> //do what you need with this object
  </tbody>
</table>

P.S. I opted for the controllerAs syntax in the modal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nullify the unfulfilled fetch call

When a value is entered in the search bar on the webpage, it gets added to a URL and used to retrieve JSON data. Everything works smoothly, but if a value is inputted that the API doesn't have information for, a null response is returned. The questio ...

Encountered an issue while attempting to import a package in ES6: 'Module specifier "vue" could not be resolved'

As I dive into Vue tutorials, I find myself facing a challenge in importing Vue into a .js file and then linking this file to my index.html. The script importation in my index.html looks like this: <script src="./js/main.js" type="module"></scrip ...

Bug Found in AngularJS v1.3.15: Text Color Rendering Glitch on Page Load with WebKit

It appears that the text colors (which should be blue) are not displaying correctly until a user hovers over the text or resizes the window. I attempted to resolve this issue by adjusting the transition property so that it triggers on hover/active states ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...

How can we determine the source website from which we were redirected?

One feature I am working on for my application is a back button. I want to be able to track where users are coming from when they land on my website from another domain. How can I determine the URL that brought them to my site? My goal is to redirect the ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Fixing issues with Ajax calls in Internet Explorer versions 7 and 8

Here is the Javascript code I have written: $("#login").click(function(){ username=$("#user_name").val(); password=$("#password").val(); $.ajax({ type: "POST", url: "login.php", data: "username="+username+"&passw ...

Need help triggering Ajax code upon clicking a link?

Can someone help me find the issue with my script? Below is the code snippet: <script> $(".icross").click(function(e){ e.preventDefault(); var obj = $(this); $.ajax({ type: "GET", url: "supprimer.php", data: 'id=&a ...

Encountering difficulties in the installation of a package within Next JS

Can anyone assist me with this issue I'm facing while trying to install styled-components on Next JS? I keep getting an error after entering npm install --save styled-components: npm ERR! Unexpected end of JSON input while parsing near '...ry.np ...

Issue with Jquery: Checkbox fails to get checked in Internet Explorer 7

Having trouble with checking a checkbox, I've attempted the following steps: $('#someId').attr('checked','checked'); $('#someId').attr('checked', true); Both of these methods are effective for I ...

Angular: Executing a function within the controller's scope and subsequently transferring it to a directive

I am currently working on evaluating a function in the parent controller and passing it into a directive. It is important that these values are watched by the digest loop and updated whenever a user makes changes. While I have resolved some initial issues ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

What can be used as an alternative to the onkeypress event for touch events?

For my text fields, I am currently utilizing the onkeypress event to validate numbers exclusively. However, this method is not effective for mobile devices (the page is designed to be responsive for both desktop and mobile use). Upon discovering that touc ...

Performing an Ajax MySQL query utilizing the text from a link as a reference, across a page

I have a page with several links. When a user clicks on a link, the text from the link is used in the WHERE clause of a MySQL query, and the result is displayed on the page using ajax. I'm trying to run different queries based on multiple ids or clas ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

When using Laravel with jQuery Ajax, the search for the file address is unsuccessful

Learning Laravel has been a challenging journey for me. I've encountered numerous problems that have made it feel like more of a hindrance than a helpful tool. But the real story lies elsewhere. Working with Laravel 4 and jQuery 2, I attempted to fet ...

D3 Chart: What is the best way to insert images into a node?

Within the jsFiddle demo provided in this query, there is code displayed. I am curious about how I can assign images to each node. var graph = { "nodes":[ {"name":"1","rating":90,"id":2951}, ] } You can access my jsFiddle Demo through this ...

What are the best circumstances for applying JavaScript in ASP.NET?

As someone who is just starting out in ASP.Net, I have been exploring Validation Controls. However, I am curious about the specific scenarios in which JavaScript would be more appropriate to use. Can anyone provide insight on this? ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...