André Kuhlmann
André Kuhlmann

Reputation: 4668

Javascript inside a Angular router

I have build a very basic Angular Router. But now that I want to interact with my elements inside that templateUrl, no javascript gets executed or those elements inside the templateUrl can not be accessed. I have copied the most of the code from this instruction, here.

My index file:

<html ng-app="myApp">

    <head></head>

    <body ng-controller="mainController">

         <a id="btnHome" href="#/">Startseite</a>
         <a id="btnPlanner" href="#/planner">LTC-Planner</a>
         <a id="btnSocial" href="#/social">LTC-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:

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

// Configure our 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 this 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>

maybe one of you got an idea or has seen an alternative.

Thanks, André

Upvotes: 2

Views: 57

Answers (1)

Gatsbill
Gatsbill

Reputation: 1790

you should try to wrap your html template in a single tag

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

And remove the script to put the logic inside your controller. Since your using angular, just use ng-click to bind click listener.

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

Upvotes: 3

Related Questions