How can we display AngularJS and XML content together effectively?

Currently collaborating with the database team, who are providing data via XML format. My task is to display different elements in the view based on their specifications.

The following code represents a dynamic table:


      <table>
        <thead>
          <tr>
            <th ng-repeat="column in cols">
              <span>{{column}}</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="row in rows">
            <td ng-repeat="column in cols"
                ng-init="isXX = column.indexOf('XX') === 0">
              <span ng-if="!isXX">{{row[column]}}</span>
              <button ng-if="isXX" class="btn btn-xs btn-blue"
                      ng-click="fillOpen()">
                  {{column.substring(3).replace('_', ' ')}}
              </button>
            </td>
          </tr>
        </tbody>
      </table>

Below is the controller snippet:


    ReportsFactory.pendingBets(reportParam).then(function(data) {
      if (data.length) {
        gridInfo = _.forEach(data, function(item) {return item;});
        $scope.rows = gridInfo;
        $scope.cols = Object.keys($scope.rows[0]);
      }
    }

In the above code snippet, ng-init specifies whether an element should be displayed as a button or not depending on the property received

I have also included a screenshot of the current view:

https://i.sstatic.net/WYf5s.png

My question is regarding how to interpret the provided XML:

[{ BET: 57635034,
  CUSTOMER: 181645,
  SPORT: 'NFL',
  'XX_FILL OPEN': '<element><element_type>WAGER_ACTION_BUTTON</element_type><element_call>fillOpen(57635034)</element_call><element_content/></element>',
  XX_VIEW: '<element><element_type>BASIC_DROPDOWN</element_type><element_call>callThisFunction()</element_call><element_content><li>1</li><li>2</li><li>3</li><li>4</li></element_content></element>',
  XX_CANCEL: '<element><element_type>BASIC_CHECKBOX</element_type><element_call/><element_content>1</element_content></element>'
}]

The XML dictates the type of HTML element to display - for example, a button for WAGER_ACTION_BUTTON and a dropdown for BASIC_DROPDOWN. Any suggestions on how to dynamically generate the correct HTML element based on this information?

Looking forward to your input!

Answer №1

It seems like you're looking to dynamically render XML or HTML content in your view. Assuming that "element" and "element type" are directives you have.

You can use the ngBindHtml directive, for example:

<div class="col-xs-offset-1 m-r-offset-8 p-t-offset-2 font-l-16">
<span mathjax-bind ng-bind-html="question.question.body"></span>
</div>

Or you could also utilize the trustAsHtml function:

<div class="col-xs-offset-1 m-r-offset-8 p-t-offset-2 font-l-16">
<span mathjax-bind ng-bind-html="trustAsHtml(question.question.body)"></span>
</div>

$scope.trustAsHtml = function (val) {
return $sce.trustAsHtml(val);
};

This will render your XML or HTML code as expected. Additionally, you can create a custom directive and use $compile as follows:

app.directive('ngHtmlCompile',function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.ngHtmlCompile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);

// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});

Simply call the ng-html-compile directive in your code - no need for $sce.

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

Real-time port communication using PHP and C++

I am working on developing a PHP application that communicates with the COM port on a local machine. The challenge I am facing is that reading from the COM port in PHP is not straightforward due to a timeout reading bug. To overcome this issue, I have imp ...

The git clone operation encounters a problem with the error message: unable to connect, connection refused on localhost port 80

Currently for my project, I'm utilizing isomorphic-git. However, when I try to implement the git.clone function, I encounter the error message Error: connect ECONNREFUSED 127.0.0.1:80. To provide an example of what I am attempting to achieve: import ...

What are some ways to improve the efficiency of my login system?

I have attempted two different methods. (1) User inputs information -> Ajax call to verify credentials -> Server sends a header, which is captured on the client side and written using document.write(). (2) User enters information -> Ajax call to ...

Using Angular's ng-repeat directive to iterate over a list of <li> elements containing strings with

Query: <li ng-repeat='msg in msgs'>{{msg}}</li> Directive: msgs=['abc','a b v', '123'] msgs.push('Something entered from textarea, possibly containing line breaks') ...

Custom components receive specific values through Styled Components

Hey there! I'm currently working on customizing the color of a button based on its type within a modal. The button can be categorized as either "Success" or "Danger": import React from "react"; import styled from "styled-components" ...

Unexpected token ')' in Unity Javascript: expecting '{' but found 'EOF'

There seems to be a syntax error on line 12 and 22, but after checking for missing or extra brackets, I am perplexed as to what is causing these errors in my update function. My goal is for the program to be capable of firing four times before needing to r ...

What is the quickest method to identify duplicate entries within a JavaScript array?

let items = ['test0','test2','test0']; In the scenario shown above, we have two duplicate elements with the value "test0". What is the most efficient way to check for this duplication? ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

Immersive animations with Chart.js

Is there a way for my pie chart to load with its animation as I scroll down the page? Here is the code I am using: <script> var ctx = document.getElementById("myPieChart").getContext("2d"); var myPieChart = new Chart(ctx, { type: 'pie&apos ...

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

Guide to altering the color of an href element when clicked using Jquery

I am looking to modify the color of the selected language when clicked. See my code snippet below: $(document).ready(function(){ $("a[href*='lang']").click(function(e) { e.preventDefault(); $('#header-top a').remove ...

Activate the action using the onclick interaction

window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false); My current setup involves an event listener that responds to a mousewheelEvent by executing a function. However, when attempting to directly trigger this function on a separa ...

Exploring the contrast: State data versus destructuring in React

I have been experimenting with some basic React code and I am puzzled by the behavior. Can anyone explain the difference between these two parts of the code: increment = () => { const { count } = this.state; // doing destructure ... this.setState({ cou ...

Issue with JavaScript removeAttribute for the "readonly" attribute not functioning as expected

Hi there, I'm new to JavaScript and I'm trying to remove the readonly attribute from some text input fields. My code seems to be working, but there's a strange behavior where the readonly attribute is removed for about 1 second and then it g ...

Validate the Start and Finish Date in a DatePicker without the need for a plugin

Utilizing Asp.Net MVC 4 in combination with JqueryUI. I have two textboxes that are equipped with datepickers. I am in need of validation where the start date can be equal to the finish date, but the finish date cannot be before the start date. Here is t ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...