【问题标题】:Should I use ng-app directive in every page for a non single page application?我应该在每个页面中为非单页应用程序使用 ng-app 指令吗?
【发布时间】:2018-04-20 01:51:23
【问题描述】:

我正在使用 MVC 为游戏开发 Web 应用程序,但视图不同(有一个 CreateGameView.html、一个 GameView.html ...),这意味着没有共享导航栏。我正在使用 AngularJS。

当单击页面中的某些按钮时,某些控制器会执行某些操作,然后加载另一个视图(html 页面)。

问题是我应该在每个使用控制器的 html 页面中使用 ng-app 指令吗?

【问题讨论】:

    标签: javascript angularjs web model-view-controller


    【解决方案1】:

    我只会使用一个ng-app 指令。而是使用 ngroute 来控制您的视图。 w3schools上有一个简短的教程:https://www.w3schools.com/angular/angular_routing.asp

    以下是它的要点。

    index.html

    <body ng-app="myApp">
    
    <!-- if you wanted a common navbar -->
    <navbar></navbar>
    
    <div ng-view></div>
    
    </body>
    

    starScreenView.html

    <p><a href="/createGame">New Game</a></p>
    <p><a href="/loadGame">Load Game</a></p>
    

    createGameView.html

    <p>This will be the create game view</p>
    <p><a href="/">Main Menu</a></p>
    <p><a href="/loadGame">Load Game</a></p>
    

    gameView.html

    <p>This will be the game view</p>
    

    app.js

    var app = angular.module("myApp", ["ngRoute"]);
    app.config(function($routeProvider) {
        $routeProvider
        .when("/", {
            templateUrl : "startScreenView.html",
            controller: "startScreenCtrl"
        })
        .when("/createGame", {
            templateUrl : "createGameView.html",
            controller: "createGameCtrl"
        })
        .when("/loadGame", {
            templateUrl : "gameView.html",
            controller: "gameViewCtrl"
        })
    });
    

    正在发生的事情是 ng-view 被替换为 templateUrl html 页面,并且该块已将控制器包裹在其周围。

    对于每个路由端点,您可以有一个页面、控制器、传递参数等。只需在 google 上搜索 ngroute 示例。

    【讨论】:

    • 但是新的 html 页面是用 ng-view 指令加载到 div 中的,对吧?我不希望新游戏和加载游戏的链接出现在加载的新页面中。
    • 是的,这些链接实际上会在 startScreenView.html 中
    • 是的,但我不希望这些链接位于 createGameView.html 或 gameView.html 中。
    • @MABC 我分解了 html 以希望使其更清晰。查看编辑。
    【解决方案2】:

    如果您必须有单独的 HTML 页面并且您计划在所有这些页面上使用 Angular,那么您需要在所有这些页面上使用 ng-app。

    否则,请使用路由器或自行设计交换页面内容的方式。如果您的页面足够简单,您可能不需要路由器的额外大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2013-11-23
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2010-12-31
      相关资源
      最近更新 更多