Android Phonegap app + AngularJS: Update $scope wi

2019-07-16 14:45发布

问题:

I created a plugin for my phonegap app, which calls a native android "DatePicker" controll. The DatePicker is invoked in this way:

There is a checkbox on the view. When the user check's the checkbox, I invoke the DatePicker. After selecting a date and pressing confirm, an event is fired an I get the date selected. The problem is, inside this event, I don't have the $scope. Even though I try to set it and it does not get updated. I imagine that this happen because the $scope is not in the context when the event is fired.

I need to have the date that the user selected to make some validation, and allow he to save the changes. Here is my view and controller:

View (shortned for simplification purpose)

    <div>
        <span>Status</span> <br />
        <label>
            <!-- When this checkbox is checked, I invoke the DatePicker-->
            <input type="checkbox" ng-model="resolved" ng-click="openCalendar()">
            <div ></div>Item Resolved
        </label>
    </div>

    <div class="center">
        <button ng-disabled="!resolved">Save</button>
        <button>Cancel</button>
    </div>

Controller:

myappControllers.controller('ItemDetailsController', 
['$scope', '$routeParams', 'Notification', function ($scope, $routeParams, Notification) {

$scope.notification= Notification.getNotification($routeParams.Id);

$scope.resolved = false;

$scope.date = '';

//This event is fired when the user check's the checkbox
$scope.openCalendar = function(){ 

    // defining options
    var options = {
      date: new Date(),
      mode: 'date'
    };

    //This event is fired when the user has selected a date on the DatePicker
    datePicker.show(options, function(date){ 

        $scope.date = date //Does not get updated!

    });
}

//Function for save button
$scope.save = function(){

   if($scope.date){
      //save the changes
   }
}

}]);

How do I handle this?

回答1:

Just add $scope.$apply() to your datePicker.show method.

datePicker.show(options, function(date){ 

    $scope.date = date;
    $scope.$apply();

});

Angular doesn't know about the change because it happens "outside", $scope.$apply() would fire a digest cycle so it can apply the changes.