您可以在不重新加载AngularJS中的控制器的情况下更改路径吗?

之前有人问过这个问题,从答案来看它看起来并不好。我想考虑一下此示例代码...


我的应用程序将当前项目加载到提供它的服务中。有几个控制器可以在不重新加载项目的情况下操纵项目数据。


如果尚未设置,我的控制器将重新加载该项目,否则,它将在控制器之间使用该服务中当前加载的项目。


问题:我想为每个控制器使用不同的路径,而无需重新加载Item.html。


1)有可能吗?


2)如果这不可能,那么与我在这里提出的相比,是否有更好的方法为每个控制器设置路径?


app.js


var app = angular.module('myModule', []).

  config(['$routeProvider', function($routeProvider) {

    $routeProvider.

      when('/items', {templateUrl: 'partials/items.html',   controller: ItemsCtrl}).

      when('/items/:itemId/foo', {templateUrl: 'partials/item.html', controller: ItemFooCtrl}).

      when('/items/:itemId/bar', {templateUrl: 'partials/item.html', controller: ItemBarCtrl}).

      otherwise({redirectTo: '/items'});

    }]);

Item.html


<!-- Menu -->

<a id="fooTab" my-active-directive="view.name" href="#/item/{{item.id}}/foo">Foo</a>

<a id="barTab" my-active-directive="view.name" href="#/item/{{item.id}}/bar">Bar</a>

<!-- Content -->

<div class="content" ng-include="" src="view.template"></div>

controller.js


// Helper function to load $scope.item if refresh or directly linked

function itemCtrlInit($scope, $routeParams, MyService) {

  $scope.item = MyService.currentItem;

  if (!$scope.item) {

    MyService.currentItem = MyService.get({itemId: $routeParams.itemId});

    $scope.item = MyService.currentItem;

  }

}

function itemFooCtrl($scope, $routeParams, MyService) {

  $scope.view = {name: 'foo', template: 'partials/itemFoo.html'};

  itemCtrlInit($scope, $routeParams, MyService);

}

function itemBarCtrl($scope, $routeParams, MyService) {

  $scope.view = {name: 'bar', template: 'partials/itemBar.html'};

  itemCtrlInit($scope, $routeParams, MyService);

}

解析度。


状态:按照接受的答案中的建议使用搜索查询,这使我可以提供不同的URL,而无需重新加载主控制器。

我的局部中的内容用 ng-controller=...


扬帆大鱼
浏览 579回答 3
3回答

慕神8447489

为什么不只是将ng-controller提升一级,<body ng-controller="ProjectController">&nbsp; &nbsp; <div ng-view><div>而且不要在路线中设置控制器,.when('/', { templateUrl: "abc.html" })这个对我有用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS