tips for modifying html element attributes using angular

I am working with an element that is automatically generated through an API call as

<a target="_blank" href="http://www.work.com/reward"><b class="orange tdu">My Work History</b></a>

and now I want to modify it like

<a ng-click="message(messageItem.id)">

essentially, I need to remove the original properties and add Angular's ng-click to it.

Unfortunately, I am unable to use JQuery for this task.

Answer №1

Here is a suggestion for your controller implementation.

1: First, select the element and remove any unnecessary attributes like

element.removeAttribute("target");

2: Next, add the required attribute to the element using

element.setAttribute('ng-click', 'loadMicrosite(messageItem.id)'); //you can concatenate strings for messageItem.id 

3: The updated element is now in the DOM but not yet connected to the scope. Utilize $compile for this task. According to the Angular documentation, $compile

Compiles an HTML string or DOM into a template and generates a template function, which can then be used to link the scope and the template together.

https://docs.angularjs.org/api/ng/service/$compile

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

app.controller('mainCtrl', function ($scope,$compile) {
  
var sNew = document.querySelector('a');
sNew.removeAttribute("target");
sNew.removeAttribute("href");
sNew.setAttribute('ng-click', 'loadMicrosite(messageItem.id)');


$compile(sNew)($scope);
  
 $scope.loadMicrosite = function(param)
 {
   alert("I am called");
 }
  
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
   <a target="_blank" href="http://sprintweb.abc.com/sos-children-s-villages-of-india-new-delhi-delhi"><b class="orange tdu">SOS Children's Villages of India</b></a>

</body>
</html>

Answer №2

To retrieve your html content from an api and display it in a new window, you can use the window.open method.

Here is an example snippet of code in html:

<a ng-click="loadMicrosite(messageItem.id)">
   <b class="blue underline">Visit SOS Children's Villages of India</b>
</a>

And here is the corresponding function in the controller:

$scope.loadMicrosite = (id) ->
  url = getURLfromServer;
  window.open(
  url,
  '_blank');

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

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

What is the best way to refresh my view model while using chained promises?

I've recently started learning about promises and I'm facing a challenge with updating an object in my view from two chained promises: function Test($resource, FC, UserDetailsService) { 'ngInject'; var self = this; se ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Ensuring that Bootstrap rows fill the entire height within a column

While working on a template with nested rows and columns in Bootstrap, the layout ended up looking like this: <div class="col-5"> <div class="row"> <div class="col-3 border border-secondary">Truck Number</div> ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

What could be causing my Discord bot to remain offline even when I run the command node main.js?

After successfully installing node.js, I proceeded to type the command 'npm init' in the command prompt and then installed discord.js. However, upon installation of discord.js, a 'node_modules' folder was not added inside the project, w ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...

What sets index.js apart from page.js in next.js?

https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts While reading through the next.js documentation, I came across an interesting point. The documentation mentions that index.js serves as the root of the directory. This mean ...

Controlling the HTML5 dialog element within a React application

Struggling to implement a basic configuration dialog with a close icon in the top-right corner using React. In other frameworks, it's easy to show/hide a dialog with .showModal()/close(), but manipulating the DOM directly in React is not recommended. ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...

Tips for retrieving console data in VueJS Data

Is there a way to review data from a form component in the console without vue taking any action? I need to receive external data and fill in the fields accordingly. I attempted to set a value using document.getElementsByName("nfe.codigo")[0].value = "000 ...

How to properly utilize $.ajaxComplete and $.ajaxError functions?

I have been utilizing the code snippet below for my ajax form submissions: $.ajax({ url: "", data: ilmoittautumisdata, type: "POST", success:function(){ }); error:function(){ }); }); However, I recall being advised to discontinue using success and erro ...

Issue with Node.js Mongoose: Attempting to store a date in UTC Timezone, but it is being saved in the local time

I am relatively new to using nodejs and mongodb. I am encountering an issue with dates while using mongoose for mongodb - whenever I attempt to save a date into the database, it automatically gets converted to the local timezone, which is not the desired b ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

A guide on utilizing Stripe's payment_intent_data feature to automatically send an email to the customer following a successful transaction

I am struggling to send an email to the client after a successful payment. The documentation mentions setting "payment_intent_data.receipt_email", but my code below is not working as expected (no emails are being received). How should I properly configur ...

Ways to retrieve a value from a JavaScript function without using the return statement

I wrote a Javascript method as follows: function ServerSideDatasource(server) { return { getRows: function (params) { var response = server.getData(params.request).then((res) => { var result = { success: true, ...