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

时间:2015-10-30 02:00:06

标签: javascript jquery html angularjs angular-ui-router

在下面的代码中,#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
.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'
        })
}])

1 个答案:

答案 0 :(得分:1)

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

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

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

虽然,我不建议这样做,因为它不是“有角度”的方式。什么会更好是像以下......

在你的视野中..

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

在你的控制器内......

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