Change the template source dynamically using angularJS

I'm working with a simple piece of code that swaps out the ng-include tag with a template based on the button clicked. You can check it out on this Plunker.

<button ng-click="template='page1'">Show Page 1 Content</button>
<button ng-click="template='page2'">Show Page 2 Content</button>

<ng-include src="template"></ng-include>

<script type="text/ng-template" id="page1">
  <h1 style="color: blue;">This is the page 1 content</h1>
</script>

<script type="text/ng-template" id="page2">
  <div id="testanglr" ng-controller="PhoneListCtrl">
    <ul>
      <li ng-repeat="phone in phones">
        <span>{{phone.name}}</span>
        <p>{{phone.snippet}}</p>
      </li>
    </ul>
  </div>
</script>

My goal is to achieve the same functionality as the "Show Page 2 Content" button but using a JavaScript function instead of Angular's HTML helper tag. In the linked Plunker, I want the third button to behave just like the second one, but this action should be triggered within the onClickHandler function rather than an alert.

Answer №1

If my understanding is correct, you are looking to make changes to Angular from outside the Angular environment. You can achieve this by following these steps:

function handleButtonClick() {
  var appElement = document.querySelector('[ng-app=myApp]');
  var appScope = angular.element(appElement).scope();
  appScope.data = 'updatedData';
  appScope.$apply();
}

http://example.com/edit/some-link

Answer №2

I'm not sure why you're looking for this specific solution, but there is a method to make it happen.

JavaScript

function handleClick() {

  var element = document.getElementById("main");
  angular.element(element).scope().template='page1';
  angular.element(element).scope().$apply();
}

If you are using jQuery, you can simply use $("#main") instead of angular.element. In angular.element, only DOM elements can be used, and selectors like ID or class have been removed from jqlite by angular. Check out the updated code here

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

Despite using preventDefault and returning false, the user is still being redirected after submitting the form

I'm in the process of trying to send a form using JQuery's .ajax function without having the user redirected upon submission. The form and backend code are both functioning as expected. However, I am encountering an issue when it comes to prevent ...

Upon initial server-side rendering load in Nuxt 3, Vercel fails to transmit the client's IP address to the Laravel backend

I'm encountering an issue with my setup where the actual client's IP address is not being forwarded correctly during the initial Server-Side Rendering (SSR) load of a page. Backend: Running Laravel on a VPS Frontend: Utilizing Nuxt 3 deployed on ...

Struggling to access JavaScript property

In my project, I have a global object called streams which contains an object named users. Within the users object, each property represents a username and stores an array of objects containing information about each user. This project is essentially a min ...

Tips on accessing the text content of a dt element with prototype

Below is some HTML code that I am working with: <dl> <dt><label>test</label></dt> <dd><input id="someid" type="checkbox" onchange="opConfig.reloadPrice()" class="product-custom-op ...

What could be causing the type error to show up in my JavaScript file?

Why is this error occurring? I am currently studying web development through Colt Steele's web bootcamp and encountered this issue. $ node user.js mongo connection is open D:\web development practice\mongoose_relationship\Models\u ...

Using Node.js and DIME to send binary data via POST requests

After reading a file that is 1740 bytes long into a Buffer called res, the length of res.length and res.toString('binary', 0, res.length).length is both determined to be 1740. A POST request is then sent using the request library. request.post ...

Building a table using a JSON object in a React component

I have been dynamically creating a table in React based on the API response received. data = {"name":"tom", "age":23, "group":null, "phone":xxx} Everything was working fine until I encountered a scenario w ...

Looking for assistance in creating an html page with a rotating CSS div containing unordered lists and list items

I am sharing the HTML content of my test page that I am looking to customize similar to some websites I have come across. My goal is to create a rotating div with an unordered list (ul li), where only three divs are displayed at a time while the rest remai ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

tips on locating the next immediate downloadable cell in a table

My table includes cells with colspan and rowspan attributes. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table border=1 id="mytable" > <tr><td>A1</td> <td> A2 < ...

I'm having trouble getting the Angular LightBox to function properly. Can anyone offer some guidance on

I've spent a good 3 hours trying to get this Demo to run on my computer, but no luck. I simply copied and pasted the code. Could it be that the references are not in the right place? Can anyone offer some assistance?? <!DOCTYPE html> <html l ...

When navigating back to the Homepage from another page, React displays the Homepage

Recently, I started learning React and following the Traversy crash course along with an additional video on React router 6+. My route setup looks like this: import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' return ( &l ...

I am trying to figure out the best way to position the navbar directly under the jumbotron in Bootstrap 4

Obtaining information is possible with Bootstrap 3, yet I am struggling to understand how to implement it with Bootstrap 4. ...

Using jQuery to detect changes in the value of form fields, excluding any changes related to display toggles

Currently, I am in the process of revamping a large form that includes various input fields and dropdown menus. The goal is to submit it via AJAX once a field loses focus but only if the value has been altered. To achieve this, I have set up a jQuery selec ...

What is causing the regular expression to fail when using the OR operator?

Here is the code snippet I've been working on: function toCamelCase(str){ var rest = str.replace((/-/)|(/_/)g, "") ; document.write(rest); } toCamelCase("the-stealth_warrior"); When running this code, I receive an error message: Uncaught Syntax ...

Sorting issue in PrimeVue DataTable is preventing the proper sorting of date columns

I am encountering an issue with sorting dates in a DataTable. The DataTable structure is as follows: <DataTable :rows = "5" :value = "apiItems" > <Column :field="initialDate" :header="Initial Date&q ...

Add up identical keys within an array containing multiple objects

I am working with an array of objects that look like this: [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'na ...

What are some ways to enhance the $http service in Angular?

At the moment, we are limited to using version 1.2.26 but we plan on upgrading to 1.2.28 once it's gemified. In the meantime, I am seeking advice on how to patch $http in order to make the short-hand method patch available. I'm relatively new to ...

Retrieve the data stored in the `frontmatter` of `.mdx` files with the help of a `.js` script

I am looking to utilize https://github.com/iamvishnusankar/next-sitemap for Sitemap generation. However, when I try using it in the regular way as shown below: next-sitemap.js module.exports = { siteUrl: 'https://example.com', generateRobots ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...