如何将变量从控制器传递到其范围之外的元素

时间:2016-03-27 14:50:50

标签: angularjs angularjs-scope angular-ui-router

我的问题最好用我的模板布局解释。

<body>

   <my-directive option1="myVar"></my-directive>

   <ui-view></ui-view>

</body>

正如您所看到的,我有一个ui视图,可以切换具有不同状态的视图/控制器。问题是这些状态中只有一个在'my-directive'的范围内包含必要的和逻辑的配置变量。如何将这些变量传递给指令?我试图避免使用$ rootScope,但它在我看来似乎是最好的选择。

1 个答案:

答案 0 :(得分:0)

有几种解决方案,它取决于您的配置变量:

如果您的配置变量在bootstrap初始化并且从不更改,则可以使用&#34;常量&#34;。

请参阅:https://docs.angularjs.org/api/auto/service/ $ provide#constant

如果您的配置变量可能会发生变化,您可以使用&#34;值&#34;

请参阅:https://docs.angularjs.org/api/auto/service/ $ provide#value

我知道的最后一种方法是使用服务

请参阅:https://docs.angularjs.org/api/auto/service/ $ provide#service

这篇文章解释了这3个功能之间的差异:https://gist.github.com/demisx/9605099

编辑:&#34;如何直接在视图中传递解决方案&#34;

一种可能的解决方案是在运行函数上初始化$ rootScope,如下所示:

angular.module('myApp')
  .run(function ($rootScope, yourConfigurationVariables) {
      $rootScope.aSpecificNameWichReferenceYourChoice = yourConfigurationVariables;
   });

请参阅此帖子:Can I directly access module constant from HTML under AngularJS