所有控制器模板中的 Angularjs 服务变量

Angularjs service vars in all controller templates

本文关键字:Angularjs 服务 变量 控制器      更新时间:2023-09-26


我对 Angularjs.
很陌生我创建了一个 Angularjs 服务来存储一些"全局"变量。它看起来像这样:

.factory('authVars', function() {
    var sdo = {
        baseBackendUrl: 'https://www.myurl.com',
        user: '',
        password: '',
        token: '',
        isLogged: false
    };
   return sdo;
})

现在我想在不同的控制器中使用ng-show/hide。

<div class="alert" ng-hide="authVars.isLogged">
    <strong>whatEver</strong>
</div>

这可能吗?还是将其存储在rootScope中更好?
对于一些帮助,我将不胜感激;-)感谢

只需将工厂注册到每个控制器即可。这是代码重用的目标服务。服务就像实用程序,您编写一次即可在许多控制器中使用它

.JS

myApp.factory('authVars', function() {
    var sdo = {
        baseBackendUrl: 'https://www.myurl.com',
        user: '',
        password: '',
        token: '',
        isLogged: false
    }; 
    return {
        getSdo: function() {
            return sdo;
        }
    };
})

function MyCtrl($scope, authVars) {
    $scope.authVars = authVars.getSdo();
}

演示小提琴

100% 可以投入使用!只是不要忘记将其注入相关控制器:

var Ctrl = function($scope,authVars){
    $scope.authVars = authVars;
}

示例:http://jsfiddle.net/cherniv/pzFrs/2/

您需要在控制器中注入服务,如下所示。

  app.controller('ctrl',function($scope, authVars){          
    $scope.authVars=authVars;   
  });

是的,由于依赖注入系统,这是可能的。
您可以在需要的每个控制器中"注入"此服务。

假设您有一个这样的模板:

<div ng-controller="MyController">
  <div class="alert" ng-hide="authVars.isLogged">
    <strong>whatEver</strong>
  </div>
</div>

然后,您必须像这样定义一个控制器:

.controller('MyController', function (authVars) {
  $scope.authVars = authVars;
});

几种方法可以在角度中使用常量:

使用角度常量

angular.module('myApp.config', []).
   constant('APP_NAME', 'MyApp');
angular.module('myApp.controllers', ['myApp.config'])
  .controller('AppCtrl', ['$scope', 'APP_NAME', function($scope, appName) {
     $scope.val = appName;
}]);

使用 angular.value

angular.module('myApp.config', []).
   value('config', {
      appName: 'AppName'
   });
angular.module('myApp.controllers', ['myApp.config'])
  .controller('AppCtrl', ['$scope', 'config', function($scope, config) {
     $scope.val = config.appName;
}]);

或者你这样做的方式,但工厂经常用于在返回配置对象之前设置一些东西,例如$inject一些依赖项(如$locale)。

此外,我经常使用指令 consts 在我想要的范围内附加常量:

angular.module('myApp.config', []).
directive('consts', function(config) {
    return {
      restrict: 'A',
      link: function($scope) {
         $scope.config = config;
      }
    }
});

然后:

<div consts>
  <h2>{{config.appName}}</h2>
</div>