1

我的导航有以下代码,我想在页面之间动态更新。

<nav ng-include="menuPath"></nav>

这是我的应用程序和路由设置

var rxApp = angular.module('ehrxApp', ['ngRoute']);

// configure our routes
rxApp.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            controller: 'mainController',
            templateUrl: '/content/views/index.html'
        })
        .when('/census', {
            templateUrl: '/content/views/admission/census.html',
            controller: 'censusController'
        })
        .when('/messages', {
            templateUrl: '/content/views/account/messages.html',
            controller: 'messagesController'
        })
        .when('/profile', {
            templateUrl: '/content/views/account/profile.html',
            controller: 'profileController'
        })
});

在我的主控制器中,我在这里设置了 menuPath 值:

rxApp.controller('mainController', function (userService, $scope, $http) {
    evaluate_size();

    $scope.menuPath = "/content/views/index.menu.html";
});

rxApp.controller('censusController', function ($scope, $http, $sce, censusService) {
    $scope.menuPath = "/content/views/admission/census.menu.html";
    evaluate_size();

});

当页面切换到人口普查视图时,它应该更改菜单。但是会发生的是第一页加载主菜单,然后无论您转到菜单的其他页面都不会更新。

4

1 回答 1

2

我想这个问题与子范围之间的原始值和原型继承有关,但需要查看更多的 html 来确定这一点。没有它,我提出了一种替代方法,可以解决您的问题并将配置全部保存在一个地方。

$routeProvider 将接受变量并将它们保留在路由上,即使 angular 不使用它们。因此我们通过包含 menuPath 来修改您的路由,如下所示:

var rxApp = angular.module('ehrxApp', ['ngRoute']);

// configure our routes
rxApp.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            controller: 'mainController',
            templateUrl: '/content/views/index.html',
            menuPath: '/content/views/index.menu.html'
        })
        .when('/census', {
            templateUrl: '/content/views/admission/census.html',
            controller: 'censusController',
            menuPath: '/content/views/admission/census.menu.html'
        })
        .when('/messages', {
            templateUrl: '/content/views/account/messages.html',
            controller: 'messagesController'
        })
        .when('/profile', {
            templateUrl: '/content/views/account/profile.html',
            controller: 'profileController'
        })
});

从每个控制器中删除设置 $scope.menuPath,然后最后在 rootScope 上添加一个监视,它将更改 $routeChangeSuccess 上的 menuPath

rxApp.run(['$rootScope', function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function(event, current) {
        if (current && current.$$route && current.$$route.menuPath) {
            $rootScope.menuPath = current.$$route.menuPath;
        } else {
            $rootScope.menuPath = '';
        }
    });
}]);
于 2014-06-13T01:47:30.150 回答