在Angular中显示/隐藏基于路线的内容,仅在刷新后有效

时间:2015-05-06 10:40:28

标签: angularjs angular-ui-router ng-show

我有一个标题+页脚,我不想在登陆(语言)页面上显示。这有效,但只有在刷新之后。解决这个问题的最佳做法是什么?

这就是我所拥有的:

<div ng-include= " 'includes/header.html ' " ng-show="{{currentPage != '/language'}}">

在我的LanguageCtrl里面有

$scope.currentPage = $location.path() === "/language";

我使用ui-router $ stateProvider分配控制器,如下所示:

$stateProvider
        .state('home', {
            url: "/",
            data: {
                rule: function($cookieStore) {
                                if ($cookieStore.get('languageCookie')) {
                                        return {
                                            toState: 'home'
                                        }
                    }

                                 else return {
                                        toState: 'language',
                                        toParams: {}
                                };
                        }
            },
            controller: "HomeCtrl",
            templateUrl: "view/home.html"
        })
        .state('language', {
            url: "/language",
            controller: "languageCtrl",
            templateUrl: "view/language.html"
        })

注意:这还没有完全发挥作用。

如何在不需要刷新的情况下完成这项工作? 我需要把它放在.run函数中吗?

4 个答案:

答案 0 :(得分:0)

它只分配一次值,您应该注意更改或使用方法返回值

<div ng-include="'includes/header.html'" ng-show="{{!isCurrentPage('/language')}}">

控制器

$scope.isCurrentPage = function(path) {
   return path == $location.path();
}

答案 1 :(得分:0)

解决方案:

身体上的控制器

<body ng-controller="routeCtrl">

ng-显示状态是否为语言

<div ng-include=" 'includes/header.html ' " ng-show="!state.includes('language')"></div>

控制器:

 .controller('routeCtrl', ['$scope', '$location', '$state', function($scope, $location, $state) {
    $scope.state = $state;
 }]);`

所以现在标题不会包含在语言页面中。

答案 2 :(得分:0)

到目前为止我找到的最佳解决方案。

<强> app.js

var app = angular.module('app', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('home', {
            url: '/',
            template: "<h1>Home</h1>"
        })
        .state('contact', {
            url: '/contact',
            template: "<h1>Contact</h1>"
        });
});

app.run(function($rootScope, $state, $location, $timeout) {
    $rootScope.$on('$stateChangeSuccess', function(event, toState){

        $rootScope.showInclude = true;

        if($state.current.name === 'contact') {
            $rootScope.showInclude = false;
        }
    });
});

您的包含

<div ng-include="'include.html'" ng-if="showInclude"></div>

http://plnkr.co/edit/pUUjhfMGKWxdwO8ENjaD?p=preview

答案 3 :(得分:0)

您可以使用isStateincludedByState过滤器在视图中处理所有内容。