[英]communicating between angularjs and javascript
如何促进HTML文档中angularjs和javascript之间的变量通信。
当前,我有一个javascript,它从外部应用程序获取输入,我需要做的是将输入(以变量的形式)传递给angularjs变量,以便在浏览器中显示信息。
无需赘述,这是我要完成的工作:
</body>
<script>
var newDepth = 10;
</script>
<div ng-controller="GaugeController as gControl">
// newDepth doesnt work here
{{gControl.setDepth(newDepth)}}
//gauge is a directive
// used for displaying the actual gauge
<gauge></gauge>
</div>
</body>
您可以通过将字符串引用传递给setDepth
方法来使用全局变量,然后使用$window['newDepth']
访问全局变量。
Angular不允许直接访问表达式内的$window
。 看这里 。
请在下面的jsFiddle中找到演示。
var app = angular.module('myApp',[]); app.controller('GaugeController', function($scope, $window) { console.log('global', $window.newDepth); this.setDepth = function(depth) { console.log(depth); // string name of global variable this.depth = $window[depth]; // access the global variable console.log(this.depth); // just a test to see that depth is correct }; this.getDepth = function() { return this.depth; }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script> var newDepth = 10; console.log(window.newDepth); </script> <div ng-controller="GaugeController as gControl" ng-app="myApp"> // newDepth doesnt work here {{gControl.setDepth('newDepth')}} {{gControl.getDepth()}} //gauge is a directive // used for displaying the actual gauge <gauge></gauge> </div>
Angular的表达式并非旨在以这种方式工作。 正如手册所说 ,
Angular不使用JavaScript的eval()来评估表达式。 而是Angular的$ parse服务处理这些表达式。
角表达式无法访问诸如窗口,文档或位置之类的全局变量。 此限制是有意的。 它可以防止意外访问全局状态-细微错误的常见来源。
而是在从表达式调用的函数中使用$ window和$ location之类的服务。 此类服务提供了对全局变量的可模拟访问。
但是,你可以指定newDepth
全局$scope.newDepth
或$rootScope.newDepth
在顶层控制器和使用它的应用范围,只要记住,这是一个黑客。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.