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

时间:2014-12-10 18:14:19

标签: javascript angularjs

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

  

TEST.HTM

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

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

2 个答案:

答案 0 :(得分:3)

我只根据文件结构将 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>

答案 1 :(得分:0)

你的代码有效,小提琴正在说话: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> 内容:

{{1}}
相关问题