我尝试在AngularJS控制器初始化中调用dart函数,但我得到ReferenceError: myFunction is not defined
。
import 'dart:js';
myDartFunction() {
return 42;
}
main() {
context['myFunction'] = (JsObject exchange) {
exchange['output'] = myDartFunction();
};
}
<!DOCTYPE html>
<html ng-app="MyApp">
<head lang="en">
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<div ng-controller="MyCtrl">
<p>{{var}}</p>
</div>
<script type="application/dart" src="index.dart"></script>
<script type="application/javascript" src="../packages/browser/dart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script>
angular.module("MyApp", []).controller('MyCtrl', function($scope) {
var exchange = {};
myFunction(exchange);
$scope.var = exchange['output'];
});
</script>
</body>
</html>
在我看来,当控制器初始化时,context['myFunction']
尚未设置。我该如何等待并初始化$scope.var
?
答案 0 :(得分:1)
我发现,可以使用window.onload
,这是在我的dart函数导出到JS后调用的。然后我使用$scope.$apply来更改我的范围变量。
angular.module("MyApp", []).controller('MyCtrl', function($scope) {
window.onload = function () {
$scope.$apply(function () {
var exchange = {};
myFunction(exchange);
$scope.var = exchange['output'];
});
}
});
答案 1 :(得分:0)
我建议在创建函数后从Dart触发一个事件,并在JavaScript中执行代码作为此事件的事件处理程序。