如何促进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>
答案 0 :(得分:0)
您可以通过将字符串引用传递给setDepth
方法并使用$window['newDepth']
访问全局变量来使用全局变量。
Angular不允许直接访问表达式内的$window
。请参阅here。
请在下面及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>
答案 1 :(得分:0)
Angular的表达式不是以这种方式工作的。作为the manual says,
Angular不使用JavaScript的eval()来计算表达式。 相反,Angular的$ parse服务处理这些表达式。
Angular表达式无法访问全局变量,如窗口,文档或位置。这种限制是故意的。它 防止意外进入全球国家 - 一个共同的来源 微妙的错误。
而是在表达式调用的函数中使用$ window和$ location等服务。这些服务提供对全局变量的可模拟访问。
但是,您可以将newDepth
全局分配给顶级控制器中的$scope.newDepth
或$rootScope.newDepth
,并在整个应用程序范围内使用它,请记住这是一个黑客攻击。