根据angularjs中的url改变body的类


Change class of body according to the url in angularjs

这是我的url

For Login - http://localhost/ang/#/login

For Dashboard - http://localhost/ang/#/dashboard

这是我的html正文标签

如果当前url是http://localhost/ang/#/login,那么正文应该有class="login-layout"标签,即

<body ng-cloak="" class="login-layout>

否则它应该有

<body ng-cloak="" class="no-skin">

我尝试在php中这样做,因为我不能接受#之后的url,就像这里所说的

在AngularJS中可以实现吗?

更新:

我试着在AngularJS中做这个

从控制器我可以得到url后#

var nextUrl = next.$$route.originalPath;                   

但是我怎么能改变类名…

我是这么做的

<body class="{{currentclass}}" ng-cloak>

现在在登录控制器中输入

$rootScope.currentclass = "login-layout";

而在其他控制器中只需执行

$rootScope.currentclass = "no-skin";

在app.run中检查登录路径

app.run(function($rootScope, $location){
rootScope.$on('$routeChangeStart', function(event, next, current){
    if ($location.path() == '/login') {
          $rootScope.currentclass = "login-layout";
    }
    else{
          $rootScope.currentclass = "no-skin";
    }
});

我需要在一个项目中做到这一点,这就是我如何做到的:

在我的主应用控制器中,我有:

// Inject the $location service in your controller
// so it is available to be used and assigned to $scope
.controller('AppCtrl', ["$scope", "$location",...
    // this_route() will be the variable you can use
    // inside angular templates to retrieve the classname
    // use it like class="{{this_route}}-layout"
    // this will give you -> e.g. class="dashboard-layout"
    $scope.this_route = function(){
         return $location.path().replace('/', '');
    };

暴露作用域上的当前路由名。

那么我的body标签就像这样:

<body ng-controller="AppCtrl" class="{{this_route()}}-view" ng-cloak>

您可以类似地使用$state读取$state.current.url并将其传递给

作用域

你可以像我下面的例子那样做

<body ng-cloak="" ng-class="bodyClass" class="login-layout>
$scope.bodyClass = "mainClass"
var nextUrl = next.$$route.originalPath;
if (..) {
   $scope.bodyClass = "sometAnotherMainClass";
}

控制器应该是这样的

angular.module('youAppName').controller('yourController', [ "$scope", function($scope) {
    $scope.bodyClass = "mainClass"
    var nextUrl = next.$$route.originalPath;
    if (..) {
       $scope.bodyClass = "sometAnotherMainClass";
    }
    }]);

我认为最"Angular"的解决方法是使用指令。最大的好处是你不必在你使用的每个控制器中设置一个作用域变量。

它看起来是这样的:

app.directive('classByLocation', ['$location', function($location) {
  var link = function(scope, element) {
    scope.$on('$routeChangeSuccess', function() {
      if ($location.path() == '/login') {
        element.removeClass('no-skin').addClass('login');
      }
      else{
        element.removeClass('login').addClass('no-skin');
      }
    });
  };
  return {
    restrict: 'A',
    link: link
  };
}]);
在你的HTML中:
<body class-by-location>

这是一个工作柱塞:http://plnkr.co/edit/zT5l6x9KYOT1qeMOxtQU?p=preview