【问题标题】:How to access AngularJS variable from template script如何从模板脚本访问 AngularJS 变量
【发布时间】:2013-06-19 19:03:41
【问题描述】:

我的控制器:

$scope.totals = totals;

我的模板(如预期的 html 注入工作):

{{totals}}

但我需要的是在模板中的脚本中访问变量totals,如下所示:

<script>
  var totals = ????;
  // do stuff with totals
</script>

我尝试了$scope.totals$totals{{totals}} 等,但无济于事。我将不胜感激,谢谢!

编辑:

以下是我的控制器和模板的 jsfiddle。我想在模板内部插入一个使用 $scope.totals 变量的脚本。

http://jsfiddle.net/38CrC/

【问题讨论】:

标签: javascript html angularjs angularjs-scope


【解决方案1】:

首先,AngularJS 背后的想法是避免这种情况。

就 AngularJS 而言,您最好重新考虑您的应用程序并使用指令将您当前编写的代码封装在脚本标签中。

但是,话虽如此,有一种方法可以访问这样的范围:

var $element = $('#elementId');

var scope = angular.element($element).scope();

您可以阅读documentation了解更多详情。

但如前所述,在大多数情况下,这不是推荐的做法。

希望有帮助!


OP 发布 jsFiddle 后更新:

为了您的方便,我在http://jsfiddle.net/jvandemo/hYnBa/1/创建了一个可用的 jsFiddle

由于您的示例有一个简单的 divng-controller 属性,您可以像这样访问范围:

<script>
    $(document).ready(function(){
        var $element = $('div[ng-controller="AdminEventsCtrl"]');
        var scope = angular.element($element).scope();
        console.dir(scope);
    });
</script>

会发生什么:

  • 您选择元素(在本例中使用 jQuery)
  • 您将元素包装为 AngularJS 元素(在元素上公开额外的方法)
  • 您在元素上调用scope() 方法
  • 然后您可以访问范围属性,例如scope.totals

希望有帮助!

【讨论】:

  • 从您的问题中,我得到以下范围:Child {$id: "006", this: Child, $$listeners: Object, $parent: Child, $$asyncQueue: Array[0]…} $$asyncQueue: Array[0] $$childHead: Child $$childTail: Child $$listeners: Object $$nextSibling: null $$prevSibling: null $$watchers: Array[7] $id: "006" $parent: Child this: Child __proto__: Child 没有我在哪里看到我想要使用的值。
  • 确保您选择了一个绑定到您希望检索的范围的元素。 AngularJS 构建了范围的层次结构,您需要选择正确的范围。您当前的示例代码不允许我查看您必须使用的选择器。如果您创建一个 plnkr,我也很乐意为您提供帮助。
  • jsfiddle.net/38CrC 我必须处理的内容有一些问题(当然是缩小了)。我希望这会有所帮助。
  • 我在jsfiddle.net/jvandemo/hYnBa/1 添加了一个有效的 jsFiddle 并用额外的代码更新了我的答案,为您提供方便。
  • 这最终不起作用。我必须使用指令来获取值,因为我永远无法找到我试图获取的值的正确范围。但是,您的回答使我朝着正确的方向前进,因此感谢您的帮助。
【解决方案2】:

OP 答案:

我最终不得不使用指令来找到我想要的值。在设置我想使用的值的控制器中,我添加了一个指令,使其看起来像这样:

'use strict';

angular.module('AdminApp')
  .controller('AdminEventsCtrl', function ($scope, collection) {
    $scope.totals = collection;
  }).directive('foo', function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs){
            //Use scope.totals here
        }
    }
});

在我的模板中我有声明:

<div foo></div>

这使我能够使用变量总计来做我需要的事情。

特别感谢 @jvandemo 帮助我得出这个答案。

【讨论】:

    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2014-07-20
    • 2019-04-08
    • 2011-08-29
    相关资源
    最近更新 更多