Angular routing with Javascript functionality

I have created a simple Angular Router, but I am facing an issue where the JavaScript is not executing or I am unable to access elements inside the templateUrl. I mostly followed the code from this tutorial, here.

Below is my index file:

<html ng-app="myApp">

    <head></head>

    <body ng-controller="mainController">

         <a id="btnHome" href="#/">Home</a>
         <a id="btnPlanner" href="#/planner">Planner</a>
         <a id="btnSocial" href="#/social">Social</a>

         <div id="main">
              <!-- angular content -->
              <div ng-view></div>
         </div>

         <script src="js/routing.js"></script>
    </body>

</html>

This is my routing.js file:

// Define the angular module
var myApp = angular.module('myApp', ['ngRoute']);

// Set up the routes
myApp.config(function($routeProvider) {
   $routeProvider

   // Route for the home page
   .when('/', {
      templateUrl: 'pages/home.html',
      controller: 'mainController'
   });
});

// Create the controller and inject angular's $scope
myApp.controller('mainController', function($scope) {
    $scope.message = 'This is the HOME page';
});

and here is the template file located at pages/home.html:

<button id="btnTest">Say Hello</button>

<script>
    var btnTest = document.getElementById('btnTest');

    btnTest.addEventListener('click', function(){
        console.log('Hello'); 
    });
</script>

If anyone has any ideas or alternatives, please share them.

Thank you, André

Answer №1

It is recommended to enclose your html template within a single tag

<div>
  <button ng-click="test()">Say Hello</button>
</div>

Furthermore, consider removing the script and moving the logic into your controller. Utilize ng-click in Angular for binding click listeners.

myApp.controller('mainController', function($scope) {
    $scope.message = 'This is the HOME page';
    $scope.test = function() {
      console.log('Hello');
    }
});

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

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...

Tips for linking two project routes in NodeJS and incorporating React (I am interested in invoking React within the NodeJS project)

I'm in the process of linking two projects, one using reactJS and the other NodeJS. Currently, NodeJS is running smoothly on localhost:3000. Next, I want to call a React application which redirects to port localhost:3001. How can I seamlessly connect ...

Retrieve the properties from within a closure function in a functional component

I have developed a simple React application using create-react-app. The app consists of a single component that takes in a value and an onClick callback. When the callback is triggered, the value increments. import React, { useState } from 'react&apos ...

What is the best way to sort through the items in a dropdown menu?

Can you help me with a scenario where I need to filter elements in a dropdown based on input given in a text box? I have tried using ng-change but it doesn't seem to work. Is there another way to achieve this? Here is the HTML code snippet: <inpu ...

Send back a result to calling function

My dilemma lies in setting the image URI on a state value called previewImage, which is located within a function. The challenge is extracting the image URI from inside the function and sending it back to the caller function to store it in the state. This ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

React: Maximum call stack size exceeded error was caught as an uncaught RangeError

I've been experimenting with React and I've managed to get the functionality I want, but it's running very slow due to an infinite loop lurking somewhere. I suspect the issue lies within the component lifecycle methods, but I'm unsure h ...

Using vue.js to sort comments based on the highest number of votes

Can someone guide me on sorting data (comments) based on the number of votes using vue.js? Much appreciated! data: { comments: [{ title: "Excellent blog post!", votes: 5 }, { title: "Interactive commenting feature in VueJ ...

Rendering Based on Conditions in React Native

I'm a beginner in the world of React Native and coding and I'm looking to display text based on certain variables (as shown below). If isPlayer === true && base.length === 1, then display x Else if isPlayer === true && base.leng ...

arranging objects based on the distance between them

Here is a JSON array I am working with: var details = [ { 'address':'Pantaloons,701-704, 7th Floor, Skyline Icon Business Park, 86-92 Off A. K. Road,Marol Village, Andheri East,Mumbai, Maharashtra 400059', 'lat':&apos ...

Serverside NodeJS with Socket.io experiencing issue with event communication from client

While attempting to set up a basic NodeJS server and Socket.io client for testing purposes involving WebSockets, I encountered an issue that seems rather silly. It's likely something silly that I've overlooked, considering I have previous experie ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

Utilize DataTables with a custom search form for enhanced data filtering

I rely on DataTables for its advanced functionality in creating tables with paging capabilities. When submitting data through a standard jQuery Ajax request using my own form, the returned data is formatted and then passed to the DataTables function to en ...

The error message [ERR_HTTP_HEADERS_SENT] is indicating that headers cannot be modified after they have already been sent to the client in a node.js and express

Attempting to retrieve data by Id from records stored in a MSSQL database. For example, trying to make a GET request in Postman like this: localhost:3200/api/v1/players. Encountering an error message: node:_http_outgoing:576 throw new ERR_HTTP_HEADERS_ ...

Instructions for adding a Key every time a user clicks the space Key within an Input field

I built a Movie Search Page with the OMDB API. My current issue is that the API returns an error when searching for a movie with more than one word because the API URL requires a + key between each word. I am looking for a way to automatically add the + ke ...

What is preventing the transfer of array[i].charAt(0).toUpperCase() to array[i][0]?

I am currently working on a JavaScript program that is designed to capitalize the first letter of each word in a string while converting every other character to lowercase. function titleCase(str) { str = str.toLowerCase(); var array = str.split(" " ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...