是否可以让 angular 处理一些路由,而 mvc 处理其他路由?

Is possible to let angular handle some routes and mvc others?

所以我正在开发一个现有的 MVC 应用程序,几天前我们添加了一个 angular 模块。我们尝试用 ajax 加载它,但 angular 拒绝加载,所以我们决定在索引上添加 angular 路由和 ng-view。问题是只有 angular 路由在工作,MVC 路由是死的。我是否需要将它们一一添加到 $routeProvider 中,这会导致大量不必要的工作?我们还尝试使用 2 进行测试,当 c# 控制器 return a View() 时,它不会加载到特定的 ng-view div 中,只是将部分加载为完整页面。

这是我的实际路由配置:

$routeProvider
      .when('/', {
          templateUrl: '/ServiceDesk/starter'
      })
          //Facturas
      .when('/app/Facturacion/MantenimientoFacturas', {
          templateUrl: '/Facturacion/MantenimientoFacturas',
          controller: 'FacturasController'
      })
          // Ordenes
          .when('/app/Facturacion/MantenimientoOrdenes', {
              templateUrl: '/Facturacion/MantenimientoOrdenes',
              controller: 'OrderController'
          });

      $locationProvider.html5Mode(true);

我希望 angular 只管理这条路线,而所有其他路线都由 MVC 管理,这是否可能或更好的方法?

由于路由的优先级取决于顺序,因此您只需要了解路由在 MVC 路由中的顺序即可。例如,它看起来像

/app/Facturacion/

是你想要Angular到运行的地方。因此,在您的 MVC 路由中,在 RouteConfig

中添加为您的第一条路由
routes.MapRoute(
    name: "ngRoute",
    url: "app/Facturacion/{*angularRoute}",
    defaults: new {controller = "Facturacion", action = "Index" }
);

所以现在只要您点击以 app/Facturacion/ 开头的路线,angular 路线就会接管。否则它将跳过并继续使用 MVC 路由。如果有一个特定的 MVC 路由使用与 angular (/app/Facturacion/) 相同的路径,请将其添加到 RouteConfig 中的 ngRoute 上方,这将继续到 运行 MVC 而不是 angular.

routes.MapRoute(
    name: "myMvcRoute",
    url: "app/Facturacion/someRoute",
    defaults: new {controller = "Facturacion", action = "SomeAction" }
);

确保在您的 FacturacionController 中索引操作 returns 视图,并在您的视图中添加您的 angular 脚本和 angular 代码。示例视图类似于

@{
   ViewBag.Title = "Facturacion";
}
@section head{
   <base href="/"> //Add a head section in your layout (make it optional)
}
@section scripts{
  @Scripts.Render("~/bundles/angularjs")
  @Scripts.Render("~/bundles/facturacionSPA")
}
<div ng-app="facturacionApp">
  <div ng-view></div>
</div>

你 Angular 路线看起来像

  $routeProvider.when('/app/Facturacion/MantenimientoFacturas', {
    templateUrl: '/Facturacion/MantenimientoFacturas',
    controller: 'FacturasController'
  }).when('/app/Facturacion/MantenimientoOrdenes', {
    templateUrl: '/Facturacion/MantenimientoOrdenes',
    controller: 'OrderController'
  }).otherwise({
    redirectTo: '/ServiceDesk/starter',
  });

此外,angular 模板应该是常规 html 文件,而不是部分视图。最好坚持 angular 用于 angular 东西和 MVC 用于 mvc 东西,在我看来不要混合它们!

编辑: 如果 '/ServiceDesk/starter' 是一个 mvc 路由并且你不想 angular 路由到它,你可以在你的 angular 控制器中做这样的事情:

if ($location.url().indexOf('/ServiceDesk/starter') >= 0 && supports_history_api()) $window.location.href = '/ServiceDesk/starter';

supports_history_api() 的代码为了完整性,这决定了我是否对 $locationProvider 使用 html5 模式,因为我需要旧的 IE 才能工作

function supports_history_api() {
  return !!(window.history && history.pushState);
}