Reputation: 4062
In the code below, the the #test
button works, but the #calendarButton
does not. There must be some reason that my header.html
cannot access my Javascript.
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Lifting Analytics </title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script type="text/javascript" src="js/angular-ui-router.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class"container" ng-app="app">
<header ng-include="'templates/header.html'"></header>
<div ui-view></div>
</div>
<button id="test">test</button> // This button works
</body>
</html>
header.html (This button doesn't work)
...
<button id="calendarButton" class="btn btn-default">Calendar</button>
...
script.js
$(document).ready(function() {
$('#test').click(function(){
console.log("in");
alert("in");
});
$('#calendarButton').click(function(){
console.log("in");
alert("in");
});
});
app.js (not sure if this is necessary)
Also, how do I refer to this file? the router? Sorry it's my first day with angular.
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html'
})
.state('record', {
url: '/record',
templateUrl: 'templates/record.html'
})
.state('calendar', {
url: '/calendar',
templateUrl: 'templates/calendar.html',
controller: function($scope){
$scope.array = ["item 1", "item 2", "item 3"]
}
})
.state('graph', {
url: '/graph',
templateUrl: 'templates/graph.html'
})
}])
Upvotes: 0
Views: 170
Reputation: 1149
If you're routing using ng-include or ng-route, the elements within those routes don't render until the applicable route is invoked. That's why the calendar button click event isn't being captured - it doesn't exist at the time you're binding..
To get it to work, you could try this..
$('body').on('click', '#calendarButton', function() {...}); //a delegate
Though, I would not recommend doing this, as it is not the "angular" way. What would be better is something like the following..
Within your view..
<button id="calendarButton" ng-click="clickFn()"/>
Within your controller...
$scope.clickFn = function() { ... }
Upvotes: 1