为了账号安全,请及时绑定邮箱和手机立即绑定

AngularJS动态路由

AngularJS动态路由

慕哥6287543 2019-11-23 10:40:58
我目前有一个内置路由的AngularJS应用程序。它可以正常工作,并且一切正常。我的app.js文件如下所示:angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).  config(['$routeProvider', function ($routeProvider) {      $routeProvider.when('/', { templateUrl: '/pages/home.html', controller: HomeController });      $routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });      $routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });      $routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });      $routeProvider.otherwise({ redirectTo: '/' });  }]);我的应用程序内置了CMS,您可以在其中复制和添加/ pages目录中的新html文件。即使对于新动态添加的文件,我仍然希望通过路由提供程序。在理想的情况下,路由模式为:$ routeProvider.when('/ pagename ',{templateUrl:'/ pages / pagename .html',控制器:CMSController});因此,如果我的新页面名称是“ contact.html”,我希望angular选择“ / contact”并重定向到“ /pages/contact.html”。这有可能吗?如果是这样怎么办?更新资料我现在在我的路由配置中有这个:$routeProvider.when('/page/:name', { templateUrl: '/pages/home.html', controller: CMSController })在我的CMSController中:function CMSController($scope, $route, $routeParams) {    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";    alert($route.current.templateUrl);}CMSController.$inject = ['$scope', '$route', '$routeParams'];这会将当前templateUrl设置为正确的值。但是,我现在想用新的templateUrl值更改ng-view。这是如何完成的?
查看完整描述

3 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

我认为最简单的方法是稍后解析路由,例如,可以通过json询问路由。确认我在配置阶段通过$ provide在$ routeProvider之外建立了工厂,这样我就可以在运行阶段甚至在控制器中继续使用$ routeProvider对象。


'use strict';


angular.module('myapp', []).config(function($provide, $routeProvider) {

    $provide.factory('$routeProvider', function () {

        return $routeProvider;

    });

}).run(function($routeProvider, $http) {

    $routeProvider.when('/', {

        templateUrl: 'views/main.html',

        controller: 'MainCtrl'

    }).otherwise({

        redirectTo: '/'

    });


    $http.get('/dynamic-routes.json').success(function(data) {

        $routeProvider.when('/', {

            templateUrl: 'views/main.html',

            controller: 'MainCtrl'

        });

        // you might need to call $route.reload() if the route changed

        $route.reload();

    });

});


查看完整回答
反对 回复 2019-11-23
  • 3 回答
  • 0 关注
  • 527 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信