JavaScript不适用于使用ng-include路由的元素

JavaScript not working for elements routed with ng-include

本文关键字:路由 元素 ng-include 不适用 适用于 JavaScript      更新时间:2023-09-26

在下面的代码中,#test按钮工作,但#calendarButton不工作。我的header.html无法访问我的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(此按钮不起作用)

...
<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(不确定是否有必要)

此外,我如何引用此文件?路由器?对不起,这是我第一天和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'
        })
}])

如果使用ng-include或ng-route进行路由,则在调用适用的路由之前,这些路由中的元素不会呈现。这就是为什么日历按钮点击事件没有被捕获的原因——在您绑定时它并不存在。。

为了让它发挥作用,你可以试试这个。。

$('body').on('click', '#calendarButton', function() {...}); //a delegate

不过,我不建议这样做,因为这不是"棱角分明"的方式。最好是以下内容。。

在你的视野内。。

<button id="calendarButton" ng-click="clickFn()"/>

在您的控制器内。。。

$scope.clickFn = function() { ... }