在Angular中修改外部模板

Changing outer templates in Angular

本文关键字:外部 修改 Angular      更新时间:2023-09-26

我正在将一个产品管理管理网站转换为使用Angular——我的所有视图(产品列表、详细信息视图、编辑视图等)都显示在我的管理页面的ng视图中。一切都好。然而,我有一个链接,每个产品,让我打印它的信息-它目前使用不同的外部模板作为其他的。

处理这个问题的角度方法是什么?

应用程序:

angular.module('myApp', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    // all routes but print use an index.html template
    $routeProvider.
      when('/', {
        templateUrl: '/partials/order/manage.html',
        controller: ManageOrderCtrl
      }).
      when('/order/:id', {
       templateUrl: '/partials/order/_view.html',
        controller: ViewOrderCtrl
      }).
      when('/order/edit/:id', {
       templateUrl: '/partials/order/_edit.html',
        controller: ViewOrderCtrl
      }).
      // I want this link to not use the same outer template (i.e. something like printer.html as well as use custom headers)
      when('/order/print/:id', {
       templateUrl: '/partials/order/_print.html',
        controller: PrintOrderCtrl
      }).
      otherwise({
        redirectTo: '/'
      });
    $locationProvider.html5Mode(true);
  }]);

管理列表:

<div ng-repeat="order in orders">
  <a title="Print product sheet" href="/order/print/{{ order._id }}"></a>
</div>

现在这将导致_print.html被放置在同一个ng-view中。我确实想让它在一个新窗口中打开-我只是做一个新的应用程序吗?

您可以编写一个服务,并在该服务内部做一个ajax调用来获取html。现在你的html将包含占位符,例如{{}},所以你需要一个模板库(例如:{{}}替换为真实的数据

factory('print', ["$window", function($window) {
/* service in charge of printing */
return function(templateUrl, context) {
    /* send a GET request to templateUrl for template, render the template with context
     * and open the content in a new window.
     */
    $.ajax({
        url: templateUrl,
        async: false,   //otherwise the popup will be blocked
        success: function(html) {
            var template = html.replace('<!DOCTYPE html>'n<html lang="en">'n', '').replace("</html>", ''),
                output = Mustache.render(template, context);
            $window.open().document.documentElement.innerHTML = output;
        }
    });
};

}]);