How to remove Cordova special events outside of Angular controller?

Imagine that I have a controller that processes, for example, viewing changes:

function Controller($scope){
    var viewModel = this;
    viewModel.goBack= function(){
        viewModel.visible = visibleLinks.pop(); //get last visible link 
        viewModel.swipeDirection = 'left';// for view change animation
    }
}

But I want to process it not only, for example, using the HTML buttons inside <body>, but also with the back button on the device. So I need to add the Event Listener for the event deviceready, as well as an explicit call $scope.$apply()for him to be called outside the context of angularjs, for example:

document.addEventListener("deviceready", function(){
        document.addEventListener("backbutton", function(){
             viewModel.goBack();
             $scope.$apply();
         }, false);
    }, false);
 }

(:)) controllerAs, , . : AngularJS styleguide $scope , - , $emit $on . , $apply(), Angular, . Service, $scope , , : $scope Angular() . : Angular JS Phonegap , $apply(), $scope . - Angular, $scope , ? .

+4
2

, $scope . , , , , $emit, $on, $watch.. $apply() .

, , . $rootScope, .

app.factory('utilService', function ($rootScope) {

    return {
        justApply: function () {
            $rootScope.$apply();
        },
        createNgAware: function (fnCallback) {
            return function () {
                fnCallback.apply(this, arguments);
                $rootScope.$apply();
            };
        }
    };
}); 
// use it   
app.controller('SampleCtrl', function(utilService) {

    var backBtnHandler1 = function () {
        viewModel.goBack();
        utilService.justApply(); // instead of $scope.$apply();
    }
    // or
    var backBtnHandler2 = utilService.createNgAware(function(){ 
        viewModel.goBack();
    });
    document.addEventListener("backbutton", backBtnHandler2, false);
});
+2

Angular $broadcast, $rootScope. , . - run, - . :

angular
.module('app', [])
.run(function ($rootScope, $document) {

    $document.on('backbutton', function (e) {
        // block original system back button behavior for the entire application
        e.preventDefault();
        e.stopPropagation();

        // forward the event
        $rootScope.$broadcast('SYSTEM_BACKBUTTON', e);
    });

})
.controller('AppCtrl', function ($scope) {

    $scope.$on('SYSTEM_BACKBUTTON', function () {
        // do stuff
       viewModel.goBack();
    });

});

, $scope.$on $scope.$apply().

:

  • - , ;
  • $document.on() , , , ; $scope.$on ;
  • , .

:

  • , , , , .

, . backbutton run . - , , , $rootScope, , "", .

deviceready, . , deviceready , AngularJS, :

document.addEventListener('deviceready', function onDeviceReady() {
    angular.element(document).ready(function () {
        angular.bootstrap(document.body, ['app']);
    });
}, false);

, , . backbutton run.

+1

Source: https://habr.com/ru/post/1605623/


All Articles