javascript - 从 AngularJS Controller 调用 Android 函数

标签 javascript android angularjs webview

我有一个问题需要帮助。我试图通过在我的前端使用 Angular Controller 来调用 android 函数,但我无法让它工作。

主要 Activity :

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

    mWebView = (WebView)findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new CustomWebViewClient());
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new AngularJSInterface(this), "Android");
    mWebView.loadUrl("http://192.168.70.101:3000/");

}

AngularJS 接口(interface):

public class AngularJSInterface {

Context mContext;

AngularJSInterface(Context c) {
    mContext = c;
}

public void showToast(String toast) {
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}

Angular Controller :

angular.module('app').controller('ComplaintCtrl', function ($scope, $http, complaintService) {

    $scope.showToast = function(toast) {
        Android.showToast(toast);
        console.log("toast");
}

});

HTML:

<button label="toast" ng-click="showToast('Visar toast från angularJS')">toast</button>

控制台错误:

ReferenceError: Android is not defined
at Scope.$scope.showToast (http://localhost:3000/scripts/controllers/addcomplaint.js:34:3)
at http://localhost:3000/bower_components/angular/angular.js:10567:21
at http://localhost:3000/bower_components/angular-touch/angular-touch.js:438:9
at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:12412:28)
at Scope.$apply (http://localhost:3000/bower_components/angular/angular.js:12510:23)
at HTMLButtonElement.<anonymous> (http://localhost:3000/bower_components/angular-touch/angular-touch.js:437:13)
at HTMLButtonElement.jQuery.event.dispatch (http://localhost:3000/bower_components/jquery/dist/jquery.js:4409:9)
at HTMLButtonElement.elemData.handle (http://localhost:3000/bower_components/jquery/dist/jquery.js:4095:28) 

这是我第一次使用这种东西,我不太确定如何实际使用它。我试过通过谷歌搜索寻找答案但没有运气。我做错了什么?

最佳答案

要么将你的 toast 函数更改为静态并直接调用它,要么先实例化它。而且,您没有名为 Android 的类,而是您创建了 AngularJSInterface。将 Android.showToast 更改为 AngularJSInterface.showToast(如果使用静态)。

关于javascript - 从 AngularJS Controller 调用 Android 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733563/

相关文章:

JavaScript:读取文件夹中的文件

javascript - 将 csv 加载到传单中并使用 proj4 转换坐标

android - READ_EXTERNAL_STORAGE 在应用程序重新启动之前未分配

java - 如何使 Horizo​​ntalScrollView 从右到左滚动 android

javascript - 链接多个 Promise(处理回调)

angularjs - 请求的资源不支持 http 方法 'OPTIONS' .?

javascript - 根据服务变量更改 CSS

javascript - jQuery 滚动仅在第一次选择后发生

android - 单击按钮更改 fragment View

javascript - 在端到端 Protractor 测试中使用 TimeShift.js