小编典典

AngularJS使用全局变量更改类

angularjs

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

这是我的 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

'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.
}]);

我有login.html,register.html和forgotpassword.html,home.html。每个人在单独的文件中都有单独的控制器。login.js,register.js,forgot.js,home.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";
        }
    }
});

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

我想要的是,当视图为登录或注册或忘记密码时,主体类应为"login- layout"。因此,我在正文中输入了class="{{bodylayout}}“。我知道可以使用全局变量来设置值。但是我不知道该怎么做。

app.js中, 我尝试了

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

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

    });

但是不知道如何使用它。


阅读 366

收藏
2020-07-04

共1个答案

小编典典

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

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

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

   //others code 
}

使用 service

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

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

});

在控制器中使用此服务

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

       //others code 
    }

HTML长什么样

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

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

2020-07-04