简体   繁体   English

如何避免AngularJS应用中的模板之间重复?

[英]How to avoid duplication between templates in an AngularJS app?

Suppose all the views in my site should include some shared content, for example a navbar at the top. 假设我网站中的所有视图都应包含一些共享内容,例如,顶部的导航栏。 How can this be acheived, without duplicating the navbar markup across all the views? 如何在不跨所有视图复制导航栏标记的情况下实现这一目标?

I'm looking for the most standard way to do this in AngularJS. 我正在寻找在AngularJS中执行此操作的最标准方法。

You can have your index page have a navbar, and footer, then have an ng-view div. 您可以使索引页面具有导航栏和页脚,然后具有ng-view div。

You'll need to include the ngRoute module, and the script tag linking to it. 您需要包括ngRoute模块,以及链接到它的脚本标签。

You'll have a div like this. 您将有一个这样的div。

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

You'll have a partialRoutes.js file looking something like this. 您将拥有一个看起来像这样的partialRoutes.js文件。

myApp.config(function($routeProvider){
  $routeProvider
    .when('/',{
        templateUrl: './partials/things.html'
    })
    .when('/stuff',{
        templateUrl: './partials/stuff.html'
    })
    .when('/otherstuff',{
        templateUrl: './partials/otherstuff.html'
    })
    .otherwise({
        redirectTo: '/',
    })
});

When you include ngRoute it will look something like this. 当您包含ngRoute时,它将看起来像这样。

var myApp = angular.module('myApp', ['ngRoute']); var myApp = angular.module('myApp',['ngRoute']); Here are the docs for ngRoute. 这是ngRoute的文档。 Hope I helped. 希望我能帮上忙。

https://docs.angularjs.org/api/ngRoute https://docs.angularjs.org/api/ngRoute

您可能想检查一下: https ://scotch.io/tutorials/angular-routing-using-ui-router“它提供了与ngRoute不同的方法,因为它根据应用程序的状态更改应用程序视图,而不是只是路线网址。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM