3

My problem is that when I try to call a javascript function that exists in my AngularJS app from within a UIWebView that function is not recognized. When I call the function in a typical html structure the function is recognized as expected. Example provided below:

OBJECTIVE-C:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // CODE GOES HERE
    _webView.delegate = self;

    // LOAD THE CHABACORP HOMEPAGE WITH INITIAL UIWEBVIEW
    NSString *fullURL = @"http://testing.com";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:requestObj];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{

    [_webView stringByEvaluatingJavaScriptFromString:@"testing()"];

}

ANGULARJS CONTROLLER:

'use strict';

angular.module('testing.controllers', [])

.controller('Testing', function($scope) {

    function testing() {
        alert('testing');
    }

});

BASIC HTML (WORKS WITH CURRENT OBJECTIVE-C):

<!DOCTYPE HTML>
<html>

<body>

    <SCRIPT>
    function testing() {
        alert('testing');
    }
    </SCRIPT>

</body>

</html> 
rjm226
  • 1,203
  • 1
  • 11
  • 21
  • 1
    You need to read up on and understand [scope in javascript](http://stackoverflow.com/questions/500431/javascript-variable-scope) – JoseM Mar 14 '14 at 14:21

1 Answers1

6

It's because your testing function isn't globally available. It's only available inside your Testing controller function. To make it globally available, you need to modify the controller to be something like this:

'use strict';

angular.module('testing.controllers', [])

.controller('Testing', function($scope) {

    window.testing = function() {
        alert('testing');
    }

});

Can't say that I recommend you to do this though, but it's hard to judge since we don't know more about why you want to do this.

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
  • I've developed an angular app, and I've wrapped it in a UIWebView in order to create a native iOS app. Basically I found no1 will use the app unless its native. So instead of just going completely native with the build I thought if there is a way to execute javascript functions from the WebView it would save me a lot of work. – rjm226 Mar 14 '14 at 14:37