1

I try to call a dart function in an AngularJS controller initialization, but I get ReferenceError: myFunction is not defined.

index.dart

import 'dart:js';

myDartFunction() {
  return 42;
}

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

My html with AngularJS:

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

It seems to me, that context['myFunction'] has not been set yet, when controller gets initialized. How can I wait for it and initialize $scope.var?

2 Answers 2

1

I found out, that it is possible to use window.onload, which is called after my dart function has been exported to JS. Then I use $scope.$apply to change my scope variable.

angular.module("MyApp", []).controller('MyCtrl', function($scope) {
    window.onload = function () {
        $scope.$apply(function () {
            var exchange = {};
            myFunction(exchange);
            $scope.var = exchange['output'];
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I would suggest to fire an event from Dart after the function was created and execute the code in JavaScript as event handler for this event.

7 Comments

What kind of event would you fire? Which code would you execute in the event handler? Where can I listen for the event, having access to my angular variable?
You can just call dispatchEvent(new CustomEvent('dart-ready')); (not tested but as far as I remember it should look like this). In JavaScript you can do something like document.addEventListener('dart-ready', doSomething, false);
All right, but how can I access my angular variable in doSomething?
If your event handler doSomething is a function of your MyCtrl controller this should be quite easy. I don't know Angular.js though and can't tell if this involves some difficulties there.
This was the hint I needed. I have to call $apply. A typic beginner's mistake.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.