AngularJS + PhoneGap相机 - 如何获得成功的范围

gui*_*tal 2 angularjs cordova

我不知道为什么但是$ scope不能用于回调相机.(OnSuccess功能)

HTML

<button ng-click="capturePhoto();">Capture</button>
<span>{{ test }}</span>
Run Code Online (Sandbox Code Playgroud)

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

    }

});
Run Code Online (Sandbox Code Playgroud)

该页面仍显示test1.难道我做错了什么?有最佳方​​法吗?

谢谢

Bor*_*ier 5

它不起作用,因为你通过插件回调退出角度摘要周期,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
    });

}
Run Code Online (Sandbox Code Playgroud)

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

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 });

}
Run Code Online (Sandbox Code Playgroud)