AngularJS + PhoneGap Camera - 如何成功获得 $scope

标签 angularjs cordova

我不知道为什么,但 $scope 不适用于相机的回调。 (OnSuccess函数)

HTML

<button ng-click="capturePhoto();">Capture</button>
<span>{{ test }}</span>

JAVASCRIPT

app.controller('myController', function($scope, $http) {

    $scope.capturePhoto = function(){

        $scope.test = "test 1";

        navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
        destinationType: Camera.DestinationType.DATA_URL });

    }

    function onSuccess(imageData) {

        var image = imageData;

        alert($scope); // [object Object]
        alert($scope.test); // test1
        $scope.test = "test 2"; // Problem: do not show on screen
        alert($scope.test); // test2

    }

});

页面仍显示 test1。难道我做错了什么?有没有最好的方法?

谢谢

最佳答案

它不起作用,因为你通过插件回调退出了 Angular 摘要循环, Angular 永远不知道有变化,并且无法更新。

最简单的方法是使用 $apply :

function onSuccess(imageData) {

    $scope.$apply(function (){
        var image = imageData;

        alert($scope); // [object Object]
        alert($scope.test); // test1
        $scope.test = "test 2"; // Problem: do not show on screen
        alert($scope.test); // test2
    });

}

在我看来,最好的方法是使用 Promise :

app.controller('myController', function($scope, $http, $q) {

$scope.capturePhoto = function(){

    $scope.test = "test 1";
    var defer = $q.defer();
    defer.promise.then(function (imageData){
         var image = imageData;

        alert($scope); // [object Object]
        alert($scope.test); // test1
        $scope.test = "test 2"; // Problem: do not show on screen
        alert($scope.test); // test2
    }, function (error){});

    navigator.camera.getPicture(defer.resolve, defer.reject, { quality: 50,
    destinationType: Camera.DestinationType.DATA_URL });

}

关于AngularJS + PhoneGap Camera - 如何成功获得 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29036940/

相关文章:

css - 如何使用angularjs在引导选项卡中设置路由

javascript - AngularJS 1 - 切换选项卡时 CSS 崩溃

cordova - 如何在 firebase 中处理推送通知

ios - 二进制被拒绝 - TabletApplicationIconHD167 保持空白

cordova - 运行cordova构建时未处理的PromiseRejectionWarning

ios - 使用 Media API 和 Web Audio API 的 PhoneGap 应用程序在录制开始时静音

javascript - 使用 angularJs 单击时更改图标

javascript - 要求未定义? Todd Motto Angular 1.5 入门教程

angularjs - 将 SignalR 与 AngularJs 集成

android - 从 Android native 代码访问在 PhoneGap 中创建的 localStorage 或 Web 数据库