AngularJS --> ng-view 不加载 js

Posted

技术标签:

【中文标题】AngularJS --> ng-view 不加载 js【英文标题】:AngularJS --> ng-view not loading js 【发布时间】:2022-01-24 00:46:59 【问题描述】:

当 day1.js 脚本加载到索引中并且如果 html 模板中的某个 sn-p 粘贴到文件中时,该代码有效,但是当我使用 ng-view 切换到页面时它不起作用使用相同的代码。我的 day1 控制器中没有任何内容。在这一点上我很迷茫,希望能得到一些见解。

我不断收到错误

day1.js:5 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

这是我的索引:

<!-- Takes in an input.txt and counts how many times the numbers increase and decrease -->
<!DOCTYPE html>
<html ng-app="adventOfCode">
  <head>
    <title>Home</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular-route.min.js"></script>
    <meta name="vieport" content="width=device-width initial scale=1" />
  </head>
  <body>
    <header><h2>Website Header</h2></header>
    <div class="column">
      <div class="links">
        <a href="#/home">Home</a><br />
        <a href="#/day1">Day 1</a><br />
        <a href="#/day2">Day 2</a><br />
      </div>
    </div>

    <!-- Where the pages change -->
    <div ng-view></div>

    <!-- Code only works as intended when this div is pasted here -->
    <div>
      <input type="file" />
      <textarea name="" id="" cols="30" rows="10"></textarea>
    </div>
    <!-- End of pasted code -->

    <footer><h3>Website footer lalalala</h3></footer>

    <script>
      var app = angular
        .module("adventOfCode", ["ngRoute"])
        .config(function ($routeProvider, $locationProvider) 
          //inject $locationProvider service
          $locationProvider.hashPrefix(""); // add configuration
          $routeProvider
            .when("/home", 
              template: "About Us",
            )
            .when("/day1", 
              templateUrl: "views/day1.html",
              controller: "day1Controller",
            )
            .when("/day2", 
              templateUrl: "views/day2.html",
              controller: "day2Controller",
            );
        );
    </script>

    <!-- Controllers -->
    <script src="js/controllers/day1Controller.js"></script>
    <script src="js/controllers/day2Controller.js"></script>

    <!-- My scripts -->
    <script src="js/day1.js"></script>
  </body>
</html>

` 这是我正在尝试运行的 javascript (day1.js):

//selecting the input and textarea elements and saving them to variables
let input = document.querySelector("input");
let textarea = document.querySelector("textarea");

input.addEventListener("change", () => 
  //returns an array of File objects
  let files = input.files;
  if (files.length == 0) return;

  //getting the first File object
  const file = files[0];

  //creating a FileReader
  let reader = new FileReader();
  reader.onload = (e) => 
    var index = 0;
    var lastLine = "";
    var currentLine = "";
    var increased = 0;
    var decreased = 0;
    var results = [];

    const file = e.target.result;
    console.log("inside onload");
    /**We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable. */
    const lines = file.split(/\r\n|\n/);
    console.log("split the lines");
    /**-------------- Our Workspace -------------- */
    lines.forEach((line) => 
      if (index === 0) 
        lastLine = line;
        console.log(line + "-->" + index);
        index++;
       else 
        currentLine = line;

        if (currentLine > lastLine) 
          console.log(line + " --> " + index + "  :increased");
          increased++;
         else if (currentLine < lastLine) 
          console.log(line + " --> " + index + "  :decreased");
          decreased++;
         else 
          console.log(line + " --> " + index);
        
        index++;
        lastLine = currentLine;
      
    );

    console.log("Number of inputs: " + index);
    console.log("How many times the inputs increased: " + increased); //1582 is too low
    console.log("How many times the inputs decreased: " + decreased);

    document.getElementById("increase").innerHTML =
      "How many times the inputs increased: " + increased;
    document.getElementById("decrease").innerHTML =
      "How many times the inputs decreased: " + decreased;

    results = slidingWindow(lines, 3);

    document.getElementById("increase_").innerHTML =
      "How many times the inputs increased: " + results[0];
    document.getElementById("decrease_").innerHTML =
      "How many times the inputs decreased: " + results[1];

    document.getElementById("Index").innerHTML = "Number of inputs: " + index;

    /**We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element. */
    textarea.value = lines.join("\n");
    console.log("joined the lines");
  ;
  reader.onerror = (e) => alert(e.target.error.name);
  reader.readAsText(file);
);

function slidingWindow(linesArray, windowSize) 
  if (windowSize < 0 || windowSize > linesArray.length) return null;
  let currentSum = 0;
  let lastSum = 0;
  let increased = 0;
  let decreased = 0;
  let results = [];
  for (let i = 0; i < linesArray.length; i++) 
    currentSum += parseInt(linesArray[i]);
    if (i >= windowSize - 1) 
      if ((lastSum === 0) && (currentSum > lastSum)) 
        console.log(currentSum + " --> " + i + "  :no change");
       else if (currentSum > lastSum) 
        console.log(currentSum + " --> " + i + "  :increased");
        increased++;
       else if (currentSum < lastSum) 
        console.log(currentSum + " --> " + i + "  :decreased");
        decreased++;
       else if ((currentSum = lastSum)) 
        console.log(currentSum + " --> " + i + "  :no change");
      
      lastSum = currentSum;
      currentSum -= linesArray[i - (windowSize - 1)];
    
  
  return (results = [increased, decreased]);

这里是 day1.html,我想用它来运行 day1.js:

<div>
    <input type="file">
    <textarea name="" id="" cols="30" rows="10"></textarea>
</div>

      <div>
          <h3>Increase or Decrease</h3>
          <h2 id="increase"></h2>
          <h2 id="decrease"></h2>
          
          <h3>Sliding window</h3>
          <h2 id="increase_"></h2>
          <h2 id="decrease_"></h2>
          <h3 id="Index"></h3>
      </div>

【问题讨论】:

在加载该视图之前元素不存在。建议您使用 angularjs 更改事件侦听器并在控制器内运行代码 【参考方案1】:

你必须使用容器来放置你的视图。ng-视图是一个像占位符一样工作的指令。它创建一个占位符,可以根据配置放置相应的视图。

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <div class="nav">
        <a href="#home" class="button">Home</a>
        <a href="#about" class="button">About</a>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div ng-view=""></div>
</div>

【讨论】:

【参考方案2】:

我的问题是我的 index.html 中没有 Jquery 库。没有它,ng-view 加载时不会执行脚本。

【讨论】:

以上是关于AngularJS --> ng-view 不加载 js的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS 使用 ng-view 在 ng-repeat 中渲染不同的模板

jQuery 选择器在 AngularJS ng-view 指令中不起作用

ng-view 不适用于 AngularJS/Express 中的部分

AngularJS:使用 ng-animate & ng-view,如何制作 3D 立方体旋转效果?

angularJS 视图view

AngularJS,ng-view + css3 关键帧与翡翠模板 - ng-cloak 不工作