AngularJS使用全局变量更改类

时间:2021-08-01 23:44:40

I just created a angularJS application.

我刚刚创建了一个angularJS应用程序。

Here is my index.html

这是我的index.html

<html ng-app="MyApp">
  <head>
    <!-- CSS files import -->
  </head>
  <body class="{{bodylayout}}">
    <div ng-view></div>
  </body>
  <--! JS imports 
   aungular.js
   app.js
   login.js
   register.js
   -->
</html>

app.js

app.js

'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
    .when('/forgotPassword', {
        templateUrl: 'forgotpassword.html',
        controller: 'forgotController'
      })
   .when('/home', {
       templateUrl: 'views/home.html',
    })
    .otherwise({
       redirectTo: '/login'
    });
//    $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);

I have login.html, register.html, and forgotpassword.html, home.html. Each one has separate Controlers in separate files. login.js, register.js, forgot.js, home.js.

我有login.html,register.html和forgetpassword.html,home.html。每个人都在单独的文件中有独立的控制器。 login.js,register.js,forgot.js,home.js.

login.js

login.js

'use strict';

angular.module('myApp').controller('LoginController', function($scope, $location, $window) {
    $scope.user = {};
    $scope.loginUser=function()
    {
        var username=$scope.user.name;
        var password=$scope.user.password;
        if(username=="admin" && password=="admin123")
        {
            $location.path( "/home" );  
        }
        else
        {
            $scope.message="Error";
            $scope.messagecolor="alert alert-danger";
        }
    }
});

Similarly, I have post methods in other controllers.

同样,我在其他控制器中有post方法。

What I want is, when the view is login or register or forgotpassword, the body class should be "login-layout". So in body I put class="{{bodylayout}}". I know using global variables, the value can be set. But I don't know how to.

我想要的是,当视图是登录或注册或忘记密码时,正文类应该是“登录布局”。所以在体内我把class =“{{bodylayout}}”。我知道使用全局变量,可以设置值。但我不知道该怎么做。

In app.js I tried this

在app.js我试过这个

angular.module('myApp').factory("myService", function(){

      return {
        sharedObject: { data: 'login-layout' }
      }; 

    });

But don't know how to use it.

但不知道如何使用它。

4 个解决方案

#1


18  

You can create global variables in two way

您可以通过两种方式创建全局变量

  • $rootScope //already mentioned @imcg
  • $ rootScope //已经提到@imcg
  • service
  • 服务

Using $rootScope you can do something like in your LoginController controller

使用$ rootScope,您可以在LoginController控制器中执行类似操作

angular.module('myApp').controller('LoginController', function($scope, $location, $window, $rootScope) {
   $scope.user = {};
   $rootScope.bodylayout = 'login-layout';

   //others code 
}

Using service

使用服务

angular.module('myApp').factory("myService", function(){

      return {
        sharedObject: { data: 'login-layout' }
      }; 

});

Use this service in your controller

在控制器中使用此服务

angular.module('myApp').controller('LoginController', function($scope, $location, $window, myService) {
       $scope.user = {};
       $rootScope.bodylayout = myService.sharedObject.data; // get data from service

       //others code 
    }

Where your HTML looks like

你的HTML看起来像什么

<body class="{{bodylayout}}">

Note in this case you need to set bodylayout in each controller otherwise it use the old value

请注意,在这种情况下,您需要在每个控制器中设置bodylayout,否则它将使用旧值

#2


10  

Try using the $rootScope:

尝试使用$ rootScope:

$rootScope.bodyClass = 'login-layout';

<body class="{{$root.bodyClass}}">

You could handle this in the individual controllers, or perhaps in your app.js by listening for routeChangeSuccess:

您可以通过监听routeChangeSuccess在各个控制器中处理,也可以在app.js中处理:

$rootScope.$on('$routeChangeSuccess', function (event, currentRoute) {
    switch(currentRoute.templateUrl) {
        case 'login.html':
        case 'register.html':
        case 'forgotpassword.html':
            $rootScope.bodyClass = 'login-layout';
            break;
        default:
            $rootScope.bodyClass = '';
            break;
    }
});

#3


7  

You could create a <body> directive that has add and remove class events that can be triggered throughout your app.

您可以创建一个指令,该指令添加和删除可在整个应用程序中触发的类事件。

angular.module('myApp').directive('body', [function(){
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.$on('body:class:add', function(e, name){
        element.addClass(name);
      };
      scope.$on('body:class:remove', function(e, name){
        element.removeClass(name);
      };
      return;
    }
  };
}]);

In your app.js config block you can set the <body> class to whatever you want with $emit

在app.js配置块中,您可以使用$ emit将类设置为您想要的任何内容

## Add class
$rootScope.$emit('body:class:add', 'login-layout')

## Remove class
$rootScope.$emit('body:class:remove', 'login-layout')

it just simply uses the angular jqLite addClass() and removeClass() and also doesn't require you to tap into $element by using the directive link function which already has dom access to the element.

它只是简单地使用角度jqLit​​e addClass()和removeClass(),并且也不需要使用已经具有dom访问元素的指令链接功能来使用$元素。

Even without $rootScope you can call it within your controllers with $scope.$emit('body:class:add', name).

即使没有$ rootScope,你也可以使用$ scope在你的控制器中调用它。$ emit('body:class:add',name)。

#4


1  

I'm not too sure the suggested answers work for Angular 1.4x but I think I have an easier solution.

我不太确定建议的答案适用于Angular 1.4x,但我认为我有一个更简单的解决方案。

You could easily add an activeTab property to your routes like this:

您可以轻松地将activeTab属性添加到您的路由,如下所示:

.when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController',
        activeTab: 'register'
      })

Then in your Controller add the $route object to your $scope:

然后在您的Controller中将$ route对象添加到$ scope:

.controller('RegisterController', ['$scope', '$route', function($scope, $route){
     $scope.$route = $route;
}])

And use ng-class on your body tag:

并在你的身体标签上使用ng-class:

<body ng-class="{'register-class' : $route.current.activeTab == 'register' }">
</body>

This way you can dynamically set a class on your body tag when you change routes. Hope this helps someone!

这样,您可以在更改路径时在body标签上动态设置类。希望这有助于某人!

#1


18  

You can create global variables in two way

您可以通过两种方式创建全局变量

  • $rootScope //already mentioned @imcg
  • $ rootScope //已经提到@imcg
  • service
  • 服务

Using $rootScope you can do something like in your LoginController controller

使用$ rootScope,您可以在LoginController控制器中执行类似操作

angular.module('myApp').controller('LoginController', function($scope, $location, $window, $rootScope) {
   $scope.user = {};
   $rootScope.bodylayout = 'login-layout';

   //others code 
}

Using service

使用服务

angular.module('myApp').factory("myService", function(){

      return {
        sharedObject: { data: 'login-layout' }
      }; 

});

Use this service in your controller

在控制器中使用此服务

angular.module('myApp').controller('LoginController', function($scope, $location, $window, myService) {
       $scope.user = {};
       $rootScope.bodylayout = myService.sharedObject.data; // get data from service

       //others code 
    }

Where your HTML looks like

你的HTML看起来像什么

<body class="{{bodylayout}}">

Note in this case you need to set bodylayout in each controller otherwise it use the old value

请注意,在这种情况下,您需要在每个控制器中设置bodylayout,否则它将使用旧值

#2


10  

Try using the $rootScope:

尝试使用$ rootScope:

$rootScope.bodyClass = 'login-layout';

<body class="{{$root.bodyClass}}">

You could handle this in the individual controllers, or perhaps in your app.js by listening for routeChangeSuccess:

您可以通过监听routeChangeSuccess在各个控制器中处理,也可以在app.js中处理:

$rootScope.$on('$routeChangeSuccess', function (event, currentRoute) {
    switch(currentRoute.templateUrl) {
        case 'login.html':
        case 'register.html':
        case 'forgotpassword.html':
            $rootScope.bodyClass = 'login-layout';
            break;
        default:
            $rootScope.bodyClass = '';
            break;
    }
});

#3


7  

You could create a <body> directive that has add and remove class events that can be triggered throughout your app.

您可以创建一个指令,该指令添加和删除可在整个应用程序中触发的类事件。

angular.module('myApp').directive('body', [function(){
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.$on('body:class:add', function(e, name){
        element.addClass(name);
      };
      scope.$on('body:class:remove', function(e, name){
        element.removeClass(name);
      };
      return;
    }
  };
}]);

In your app.js config block you can set the <body> class to whatever you want with $emit

在app.js配置块中,您可以使用$ emit将类设置为您想要的任何内容

## Add class
$rootScope.$emit('body:class:add', 'login-layout')

## Remove class
$rootScope.$emit('body:class:remove', 'login-layout')

it just simply uses the angular jqLite addClass() and removeClass() and also doesn't require you to tap into $element by using the directive link function which already has dom access to the element.

它只是简单地使用角度jqLit​​e addClass()和removeClass(),并且也不需要使用已经具有dom访问元素的指令链接功能来使用$元素。

Even without $rootScope you can call it within your controllers with $scope.$emit('body:class:add', name).

即使没有$ rootScope,你也可以使用$ scope在你的控制器中调用它。$ emit('body:class:add',name)。

#4


1  

I'm not too sure the suggested answers work for Angular 1.4x but I think I have an easier solution.

我不太确定建议的答案适用于Angular 1.4x,但我认为我有一个更简单的解决方案。

You could easily add an activeTab property to your routes like this:

您可以轻松地将activeTab属性添加到您的路由,如下所示:

.when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController',
        activeTab: 'register'
      })

Then in your Controller add the $route object to your $scope:

然后在您的Controller中将$ route对象添加到$ scope:

.controller('RegisterController', ['$scope', '$route', function($scope, $route){
     $scope.$route = $route;
}])

And use ng-class on your body tag:

并在你的身体标签上使用ng-class:

<body ng-class="{'register-class' : $route.current.activeTab == 'register' }">
</body>

This way you can dynamically set a class on your body tag when you change routes. Hope this helps someone!

这样,您可以在更改路径时在body标签上动态设置类。希望这有助于某人!