除非刷新,否则 AngularJS 不会运行控制器

AngularJS won't run controller unless refreshed

本文关键字:运行 控制器 AngularJS 否则 刷新      更新时间:2023-09-26

非常简单(下面的代码)。我有两个html页面,test.htm和ang.htm。我从测试开始.htm只有一个指向 ang.htm 页面的超链接。ang.htm 包含角度 js,它有一个简单的控制器来执行 Hello World。我单击超链接以导航到 ang.htm。但是,我需要刷新 ang.htm 页面才能运行角度代码。为什么?

测试.htm

<html>
<body>
<a href="http://localhost/ang.htm">Click</a>
</body>
</html>

昂.htm

<html>
<body ng-app="testApp" ng-controller="testController">
    {{hello}}
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
  <script>
        angular.module("testApp", []);
        angular.module( "testApp" ).controller( "testController", function( $scope )
        {
            $scope.hello = "Hello world";
        }); 
    </script>
</body>
</html>

我只根据文件结构将 localhost/ang.htm 更改为 /ang.htm。它按预期工作。

使用Firebug进行调试对您来说将非常有帮助。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
    </head>
    <body>
        <a href="/ang.htm">Click</a>
    </body>
</html>

你的代码有效,小提琴在说话:http://jsfiddle.net/m7beqvaf/

{{hello}}令牌可能不会在页面显示加载后立即替换,但仅此而已。导航到ang.htm不是问题。

请注意,我在小提琴中复制/粘贴了您的ang.htm内容:

<body ng-app="testApp" ng-controller="testController">
    {{hello}}
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
  <script>
        angular.module("testApp", []);
        angular.module( "testApp" ).controller( "testController", function( $scope )
        {
            $scope.hello = "Hello world";
        }); 
    </script>
</body>