我不知道为什么,但 $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/