1

我尝试在 AngularJS 控制器初始化中调用 dart 函数,但我得到ReferenceError: myFunction is not defined.

索引.dart

import 'dart:js';

myDartFunction() {
  return 42;
}

main() {
  context['myFunction'] = (JsObject exchange) {
    exchange['output'] = myDartFunction();
  };
}

我的 AngularJS 的 html:

<!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

4

2 回答 2

1

我发现可以使用window.onloaddart 函数导出到 JS 后调用它。然后我使用$scope.$apply来更改我的范围变量。

angular.module("MyApp", []).controller('MyCtrl', function($scope) {
    window.onload = function () {
        $scope.$apply(function () {
            var exchange = {};
            myFunction(exchange);
            $scope.var = exchange['output'];
        });
    }
});
于 2014-10-05T11:16:59.693 回答
0

我建议在创建函数后从 Dart 触发一个事件,并在 JavaScript 中执行代码作为该事件的事件处理程序。

于 2014-10-04T20:50:30.833 回答