简体   繁体   English

访问视图中的AngularJS变量?

[英]Accessing AngularJS variable in view?

Consider basic AngularJS application with just one controller. 考虑只有一个控制器的基本AngularJS应用程序。 Inside the controller I have set-up "myVariable" to hold a value "Test". 在控制器内部,我设置了“ myVariable”以保存值“ Test”。

I am given an inline JavaScript code in the view and I need to call a function samplefunction which takes a parameter using myVariable . 我在视图中获得了内联JavaScript代码,我需要调用一个函数samplefunction ,该函数使用myVariable接受参数。

/* Controllers */

angular.module('myApp.controllers', [])
    .controller('MainCtrl', ['$scope', function($scope) {

        $scope.myVariable = "Test";

    });

In the view, in the html file, this is what I need to do: 在视图中,在html文件中,这是我需要做的:

<script type="text/javascript">

    var param1 = {{myVariable}};   /* <-- how to make this work?  */
    samplefunction( param1 );   

</script>

It doesn't work though. 虽然不行。 I just need to assign myVariable value to the param1 . 我只需要将myVariable值分配给param1 I also tried something like: 我也尝试过类似的方法:

...
var param1 = angular.element(document.getElementById("mainBody")).scope().myVariable
...

But this didn't work either. 但这也不起作用。 Please, note that I cannot touch the given JS code that I am calling in the view. 请注意,我无法触摸视图中调用的给定JS代码。

Anyone knows how to solve this simple issue? 有谁知道如何解决这个简单的问题?

From my POV what you are doing shouldn't be done. 从我的观点来看,您不应做的事情。 The closest correct approach should be: 最接近的正确方法应该是:

Setting your view with a value in the way angular was meant to be used: 使用您应该使用的角度值来设置视图

<input type="text" ng-model="myVariable" id="myVar" />

and iff you want to you get your var value get it from the view like: 如果您想要获取var值,请从如下视图中获取它:

<script type="text/javascript">  
    var param1 = document.getElementById("myVal").value;
    samplefunction( param1 );   
</script>

Online Demo 在线演示

将var传递给$ window以将其公开给您的JS。

$window.myVariable = $scope.myVariable;

What about binding the scope variable to a data-something attribute on an element in your view, and then pull it using Jquery in your external script tag? 将范围变量绑定到视图中元素上的data-something属性,然后在外部脚本标签中使用Jquery将其拉出,该怎么办?

<script type="text/javascript">  
    var param1 = $("#someId").data("myValue");
    samplefunction( param1 );   
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM