I'm trying to pass a value from swift to angularJS. The following is the swift code that calls the javascript function:
let userScriptSetToTrue = WKUserScript(
source: "setTrackingToggleToTrue();",
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
contentController.addUserScript(userScriptSetToTrue)
...
let js = "setTrackingToggleToTrue();"
self.webView?.evaluateJavaScript(js) {
(_, error) in print(error)
}
And then the javascript calls the angular controller function:
<script>
function setTrackingToggleToTrue() {
angular.element(document.getElementById('trackingToggle')).scope().setTracking(true);
}
</script>
But I got the following error in the javascript side:
TypeError: undefined is not an object (evaluating 'angular.element(document.getElementById('trackingToggle')).scope().setTracking')
It seems the document.getElementById('trackingToggle') is not available but I can see the following in the safari web inspector elements tab
<div class="list-group-item">
<tracking-toggle-button
id="trackingToggle"
state="trackingEnabled"
class="pull-right"
on-toggle="updateTrackingPreference(newState);">
</tracking-toggle-button>
<label class="tracking-label">My Location</label>
</div>
What would be the reason for this error? or is there a better way to pass a value from swift all the way to angular controller?
Update The angular app is using UI routing and loads page content from different templates based on routing. I later find out the function setTrackingToggleToTrue() is called before its template is loaded and thus no trackingToggle is available at function call. Is there another way to call an angular function outside the controller without referencing any document element?
Thanks.