如何从模板脚本访问 AngularJS 变量 [英] How to access AngularJS variable from template script

查看:16
本文介绍了如何从模板脚本访问 AngularJS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器:

$scope.totals = totals;

我的模板(对于 html 注入按预期工作):

{{totals}}

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

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

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

http://jsfiddle.net/38CrC/

解决方案

OP 答案:

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

'use strict';angular.module('AdminApp').controller('AdminEventsCtrl', function ($scope, collection) {$scope.totals = 集合;}).directive('foo', function(){返回 {限制:'A',链接:功能(范围,元素,属性){//这里使用scope.totals}}});

在我的模板中我有声明:

这让我能够用可变总数做我需要的事情.

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

My controller:

$scope.totals = totals;

My template (works as expected for html injection):

{{totals}}

But what I need is to access the variable totals in a script in the template, like so:

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

I've tried $scope.totals, $totals, {{totals}}, etc, with no avail. I would appreciate any insight, thanks!

EDIT:

The following is a jsfiddle of my controller and template. Inside of the template I'm wanting to insert a script that uses the $scope.totals variable.

http://jsfiddle.net/38CrC/

解决方案

OP Answer:

I ended up having to use a directive to find the value I wanted. In the controller that set the value I wanted to use I added a directive so that it looked like this:

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

In my template I had the declaration:

<div foo></div>

This gave me the ability to do what I needed with the variable totals.

Special thanks to @jvandemo for helping me arrive at this answer.

这篇关于如何从模板脚本访问 AngularJS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆