检查angularjs中的条件

Mat*_*van 7 javascript if-statement conditional-statements angularjs

基本上我有一个工厂

angular.module('app').factory('gService',gService);
function gService($filter, $window) {
    function confirmDialog(message, success, fail) {
        var confirmMessage = navigator.notification.confirm(
                message,
                onConfirm,
                '',
                [$filter('translate')('OK'), $filter('translate')('CANCEL')]
            );
        function onConfirm(index) {         
            return index === 1 ? success() : fail();
        }
        return confirmMessage;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果执行或不执行功能,我想检查此工厂外的条件

if(gService.confirmDialog.onConfirm){

}
Run Code Online (Sandbox Code Playgroud)

这不起作用.如何检查以角度执行的功能?

Bur*_*dız 5

EMIT& BROADCAST

如果你检查onConfirm它将控制的事件是在语句wroten的对象上onConfirm定义的函数gService.confirmDialog.这不是异步和承诺的工作.

if(gService.confirmDialog.onConfirm){

}
Run Code Online (Sandbox Code Playgroud)

您需要先通知您的听众.之后听那个事件去做你的工作.

你可以broadcastemit一个事件来作用域是等待onConfirm事件.

   angular.module('app').factory('gService',gService);
    function gService($rootScope, $filter, $window) {
        function confirmDialog(message, success, fail) {
            var confirmMessage = navigator.notification.confirm(
                    message,
                    onConfirm,
                    '',
                    [$filter('translate')('OK'), $filter('translate')('CANCEL')]
                );
            function onConfirm(index) {
                var result = index === 1 ? success() : fail();
                $rootScope.$emit('onConfirm', result); 
                //or
                //$rootScope.$broadcast('onConfirm', result); -> this goes downwards to all child scopes. Emit is upwarded.

            }
            return confirmMessage;
        }
    }
Run Code Online (Sandbox Code Playgroud)

之后,您应该检查是否onConfirm触发了事件.这是你需要的控制.

function onConfirmFunction( result ){ //You will get the success or fail methods result here... };

$rootScope.$on('onConfirm', onConfirmFunction);
Run Code Online (Sandbox Code Playgroud)