How can JSON be passed to AngularJS in an Android web browser?

I am trying to use Android Webview to display some “active” content (sets of images that vary depending on some input settings). Content will be local (offline).

I would like to use Angular.js to control the media that will be displayed on the page.

So to the problem ... how will my Angular application get JSON data at startup? The problem I see is that web browsing prevents Angular from being lazy to upload additional files (I already encountered this when trying to use html templates for a custom directive, which required the inclusion of HTML templates in a single HTML file).

My activity in Android might write parameters somewhere, but how can Angular read them? In other words, is there a way to configure web view security that prevents Angular.js from being too lazy to load additional files?

+4
source share
1 answer

, . , Java Java, JavaScript ( @JavascriptInterface). AngularJS, JSON (. JavascriptInterface: http://developer.android.com/guide/webapps/webview.html). , , .

. .

MainActivity.java

public class MainActivity extends Activity {
    private String MY_JSON_EXAMPLE = "{\"name\":\"John Doe\",\"email\":\"jdoe@testco.com\"}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView wv = (WebView) findViewById(R.id.myWebView);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.addJavascriptInterface(this, "AndroidMainAct");
        wv.loadUrl("file:///android_asset/mypage.html");
    }

    @JavascriptInterface
    public String getMyJSONData() {
        return MY_JSON_EXAMPLE;
    }
}

mypage.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>Hello World, AngularJS</title>
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <h3>Load Test</h3>
    <div ng-controller="MyController">
        <div id="dataWaiting" ng-show="!myData.length">
            Loading JSON...
        </div>
        <div id="dataLoaded" ng-show="myData.length">
            Data Loaded: {{myData}}
        </div>
    </div>
</body>
</html>

app.js

var myApp=angular.module('myApp',[]);

myApp.controller('MyController', ['$scope', function($scope) {
    $scope.myData = '';

    this.loadData = function() {
        // get the data from android
        return AndroidMainAct.getMyJSONData();
    };

    $scope.myData = this.loadData(); // load data on instantiation
}]);

android JavascriptInterface .

+5

All Articles