Angularjs面包屑返回带有参数的主页

时间:2015-01-09 11:32:12

标签: javascript angularjs breadcrumbs

我想要像以下那样使用面包屑:Home / Cars / Audi / T8,其中Home,Cars和Audi发送回HomePage但具有不同的参数,例如:汽车复选框点击等。

我将AngularJS与ui.router和ncy-angular-breadcrumb一起使用。

$stateProvider
    .state('main',{ 
        url: '/',
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        ncyBreadcrumb: {
            label: 'HomePage'
        }
    })

    .state('main.type',{
        controller: function($scope, breadcrumbsFctry) {
            $scope.defaultType = 'car';
        },
        ncyBreadcrumb: {
            label: '{{defaultType}}',  
            parent: 'main'
        }
    })

    .state('main.type.make',{
        controller: function($scope, breadcrumbsFctry) {
            $scope.defaultMake = 'audi';
        },
        ncyBreadcrumb: {
            label: '{{defaultMake}}',
            parent: 'main.type'
        }
    })
    .state('car', {
        url: '/ad/:name-:id',
        templateUrl: 'views/ad/ad.html',
        controller: 'AdCtrl',
        ncyBreadcrumb: {
            label: ':name',
            parent: 'main.type.make'
        }
    })

工厂:

.factory('breadcrumbsFctry', function () {

        var type = '';
        var make = '';

        return {

        };

    });

如何通过不同控制器的状态共享参数?

2 个答案:

答案 0 :(得分:1)

您可以将相关数据保存在专用服务中,也可以使用本地JS存储服务,例如sessionStorage或localStorage。

服务是单件,可用于在控制器之间共享数据。

在此处阅读sessionStorage和localStorage:https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

答案 1 :(得分:1)

我不确定这是否会对您的情况有所帮助,但我已使用标准ngRoute为我的网站构建了面包屑我没有使用过ui-router所以这可能不适用但是你可以给它去吧。我在我的路线中设置了一些选项,如:

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){

    $routeProvider.

    when('/blog/:slug', {
        templateUrl: 'app/pages/blog/views/blog.single.view.html',
        controller: 'blog',
        label: 'postTitle' //this is dynamic /some-post-slug/that-matches-postTitle/
    }).

    when('/blog', {
        templateUrl: 'app/pages/blog/views/blog.index.view.html',
        controller: 'blog',
        label: 'blog'
    });

}]);

然后我为面包屑设置了自定义工厂和指令:

app
    .factory('breadcrumbs', ['$rootScope', '$route', 'hitch', function ($rootScope, $route, hitch) {

        var service = {

            breadcrumbs: [],

            build: function() {

                //If active route
                if ($route.current && $route.current.originalPath) {

                    this.breadcrumbs = [];

                    var params = $route.current.params,
                        urlParts = $route.current.originalPath.split('/');

                    //Split up the path to get parent route /parent/child - [parent, parent/child]
                    angular.forEach(urlParts, hitch(this, function(part, index) {

                        var isParam = function(part){ //Test if this url part is a param
                                return part[0] === ':' && typeof params[part.substring(1)] !== 'undefined' ? params[part.substring(1)] : false;
                            },
                            pathWithParam = '', //Full route with param still intact as '/:param'
                            pathWithQuery = ''; //Full route with param as query '/someQuery'

                        //For each url part under this index
                        for(var i=0;i<=index;i++){

                            //Make path with params
                            pathWithParam += urlParts[i];

                            //Make path with query
                            if(isParam(urlParts[i])){
                                pathWithQuery += isParam(urlParts[i]);
                            } else {
                                pathWithQuery += urlParts[i];
                            }

                            //If not last in url add trailing slash
                            if(i !== index) { 
                                pathWithParam +='/';
                                pathWithQuery +='/';
                            }

                        }

                        //Make sure router and label exists for this part
                        if ($route.routes[pathWithParam] && ($route.routes[pathWithParam].label || param)) {
                            this.breadcrumbs.push({
                                path: pathWithQuery,
                                label: $route.routes[pathWithParam].label || param,
                                param: isParam(part)
                            });
                        }

                    }));

                }

            },

            //Improve this
            getDynamicLabel: function() {
                if (this.dynamicLabels) {
                    //Each label
                    for (var key in this.dynamicLabels) {
                        //Each breadcrumb
                        for (var index in this.breadcrumbs) {
                            //If using dynamic label set as label
                            var breadcrumb = this.breadcrumbs[index];
                            if (breadcrumb.label === key) {
                                breadcrumb.label = this.dynamicLabels[key];
                            }

                        }

                    }
                }
                return this.breadcrumbs;
            }

        };

        $rootScope.$on('$routeChangeSuccess', function() {
            service.build();
        });

        $rootScope.$watch(function(){ return service.dynamicLabels; }, function() {
            service.build();
        });

        service.build();

        return service;

    }])
    .directive('breadcrumbs', function() {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ul class="breadcrumbs"><li ng-repeat="breadcrumb in breadcrumbs.getDynamicLabel() track by breadcrumb.path" ng-class="{ active: $last }"><a ng-if="!$last" ng-href="{{ breadcrumb.path }}" ng-bind="breadcrumb.label" class="margin-right-xs"></a> <span ng-if="!$last"> > </span><span ng-if="$last" ng-bind="breadcrumb.label"></span></li></ul>',
            replace: true
        };
    });

然后您可以在视图<breadcrumbs></breadcrumbs>中使用breadcrumb指令,该指令将跟踪您当前的路线及其结构route/route2/route3您还可以通过包含工厂来设置动态标签:< / p>

app.controller('blog', [
    '$scope', 
    '$routeParams', 
    'api', 
    'breadcrumbs', 
function($scope, $routeParams, api, breadcrumbs){

    api.blog.getPost({slug:$routeParams.slug}).then(function(response){
            breadcrumbs.dynamicLabels = {'postTitle': response.data.title};
        }, function(error){
            console.log(error);
        });

}]);