从 AngularJS 控制器调用 Android 函数

Posted

技术标签:

【中文标题】从 AngularJS 控制器调用 Android 函数【英文标题】:Calling an Android function from AngularJS controller 【发布时间】:2014-12-31 05:59:39 【问题描述】:

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

主活动:

@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接口:

public class AngularJSInterface 

Context mContext;

AngularJSInterface(Context c) 
    mContext = c;


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

角度控制器:

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) 

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

我已将 showToast 方法更改为静态,并将 Angular.showToast() 替换为 AngularJSInterface。 showToast(),虽然我仍然得到同样的错误(AngularJSInterface 没有定义)。我究竟应该如何实例化它? AngularJSInterface myInterface = new AngularJSInterface(); myInterface.showToast();

以上是关于从 AngularJS 控制器调用 Android 函数的主要内容,如果未能解决你的问题,请参考以下文章

如何从angularjs中的另一个控制器调用函数

如何从 AngularJS 控制器正确调用 jQuery

如何从AngularJS中的另一个控制器调用函数? [复制]

从angularjs中的服务调用控制器函数

从 index.html javascript 调用 angularJS 控制器函数

在AngularJs中从控制器调用服务时,从$ get factory方法返回一个值