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

Showing / hiding content based on route in Angular, only works after refresh

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

这是我得到的:

<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"
        })

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

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

它只分配一次值,你应该观察变化或使用方法return值

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

控制器

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

解决方案:

控制器在 body

<body ng-controller="routeCtrl">

ng-show 如果状态不是语言

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

控制器:

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

所以现在 header 没有包含在语言页面中。

迄今为止我找到的最佳解决方案。

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

您可以使用 isStateincludedByState 过滤器在视图中处理这一切。