AngularJS - 为所有应用程序环境动态设置配置参数

时间:2014-01-20 09:47:13

标签: javascript angularjs config params

您好我正在尝试设置我需要的应用程序配置参数(全局配置参数)。

我试着这样:

http://pastebin.com/PdQrzLT5

然后

<html ng-controller="ConfigController">

但是这不起作用,因为每次刷新页面或每次路由更改时我都需要刷新$ location。$$路径。

我想设置一个配置参数列表,使它们全局化,可以将它们用于视图中,也可以在app.js enteire文件中使用它们。

你通常怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用services,例如:

var cmnApp = angular.module('cmnApp',[]);
cmnApp.factory('UserService', function() {
  return {
      name : 'Some Name'
  };
});

并在某些控制器中:

function someCtrl($scope, UserService) {
    $scope.name = UserService.name;
}

答案 1 :(得分:1)

解决方案:

  • 我使用$rootScope进行全局配置(不需要其他控制器)
  • 应使用 $routeChangeStart / $routeChangeSuccess来更新全局路由配置。
  • 使用$location.path()代替$location.$$path
  • 使用$location.url()代替$location.$$url

您可以在运行块中收听$routeChangeStart event,如下所示:

app.run(function($rootScope, $location){
    var update =  function (){
      $rootScope.config = {
        appname: "Ouch" ,
        appurl: $location.url(),
        apppath: $location.path()
      }

    }  
    $rootScope.$on('$routeChangeStart', update)
    update();
})

这是最佳做法吗?

  • 我的方法是使用什么使我的应用程序简单明了。
  • 如果我的全局对象必须绑定在我视图中的所有位置,那么$rootScope就是粘合剂。
  • 如果我只需要将值绑定到某些元素,我会在指令中使用$route events

带指令的示例

app.directive('routeConfig', function($rootScope, $location){   
    return {
        scope: {},
        templateUrl: "config-route.html",
        link: function(scope, elm, attrs){

            var update =  function (){
              $scope.config = {
                appname: "Ouch" ,
                appurl: $location.url(),
                apppath: $location.path()
              }

            }  

            $scope.$on('$routeChangeStart', update)
            update();
        }
    }
});

<强>配置-route.html:

<h1>route:</h1>
<ul>
  <li> name: {{ config.appname}} </li>
  <li> url: {{ config.appurl}} </li>
  <li> path: {{ config.apppath}} </li>
</ul>