【问题标题】:Javascript inside a Angular routerAngular 路由器中的 Javascript
【发布时间】:2016-08-28 15:10:25
【问题描述】:

我已经构建了一个非常基本的 Angular 路由器。但是现在我想与该 templateUrl 中的元素进行交互,没有 javascript 被执行,或者无法访问 templateUrl 中的那些元素。我已经复制了这条指令中的大部分代码,here

我的索引文件:

<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>

这是我的 routing.js 文件:

// 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';
});

这是位于 pages/home.html 的模板文件:

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

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

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

也许你们中的某个人有一个想法或已经看到了替代方案。

谢谢, 安德烈

【问题讨论】:

标签: javascript angularjs routing


【解决方案1】:

你应该尝试将你的 html 模板包装在一个标签中

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

并删除脚本以将逻辑放入控制器中。由于您使用角度,只需使用 ng-click 绑定点击监听器。

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

【讨论】:

  • 感谢您的回答@Gatsbill。 dfsq 批评了我创建路由器的方式。你的方法是什么?
  • 使用 Angular,您可以像使用 ngRouter 一样使用或使用 ui-router,但无论如何两者都可以使用。不知道他的意思是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多