最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check condition in angularjs - Stack Overflow

programmeradmin1浏览0评论

Basically i have a factory

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

I want to check condition outside this factory, if the functions are executed or not

if(gService.confirmDialog.onConfirm){

}

this does not work. How do i check function which is executed in angular?

Basically i have a factory

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

I want to check condition outside this factory, if the functions are executed or not

if(gService.confirmDialog.onConfirm){

}

this does not work. How do i check function which is executed in angular?

Share Improve this question edited Jul 17, 2017 at 11:27 Jesus Rodriguez 12k9 gold badges65 silver badges89 bronze badges asked Jul 14, 2017 at 5:16 MatarishvanMatarishvan 2,4323 gold badges42 silver badges70 bronze badges 9
  • what is index there?? – Escoute Commented Jul 14, 2017 at 5:21
  • Its from the inbuit function. – Matarishvan Commented Jul 14, 2017 at 5:22
  • Did you get any error in the console? Where did you write the if statement.? You have to return the function in the service. I have written a controller and injected the service. Called the function service function. It is working. – Ramu Achala Commented Jul 14, 2017 at 5:25
  • Its actually a popup.. I am checking if condition outside this factory, so i'm using gService.confirmDialog.onConfirm – Matarishvan Commented Jul 14, 2017 at 5:27
  • 1 @Matarishvan Something is not clear in your question. Please, I'm asking you to edit and explain what exactly are you trying to achieve, we need more macro details - Do you want to show this message only once and then check what was the check if the user confirmed it or not? You need to add context. That's will help us give you better solution. Thanks – Alon Eitan Commented Jul 16, 2017 at 14:12
 |  Show 4 more comments

6 Answers 6

Reset to default 6 +50

EMIT & BROADCAST

If you check onConfirm event that it will controll is onConfirm function defined on gService.confirmDialog object where the statement wroten. It is not async and promised job.

if(gService.confirmDialog.onConfirm){

}

You need to notify your listeners first. After that listen that event to do your job.

You can broadcast or emit an event to scopes that waiting for onConfirm event.

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

After that you should check if onConfirm event is triggered. This does the controll you need.

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

$rootScope.$on('onConfirm', onConfirmFunction);

Why don't you do this.

angular.module('app').factory('gService',gService);
function gService($filter, $window) {
    var obj = {
        confirmDialog : confirmDialog,
        onConfirm : onConfirm,
    }
    obj.executed = false;
    function confirmDialog(message, success, fail) {
        var confirmMessage = navigator.notification.confirm(
                message,
                onConfirm,
                '',
                [$filter('translate')('OK'), $filter('translate')('CANCEL')]
            );
        function onConfirm(index) {         
            if(index===1){
                //I dont know you want function or returned value of function but you can use success() as well
                obj.executed = success;
                return success();
            }else{
                obj.executed = fail;
                return fail();
            }
        }
        return confirmMessage;
    }
    return obj;
}

you can check now..

if(gService.executed){

}

and I dont know if you forgot but you haven't returned anything from factory.

Try the following:

angular.module('app').factory('gService', gService);
function gService($filter, $window) {
  var observers = [];
  function observeNotify(callback) {
    observers.push(callback);
  }
  function confirmDialog(message, success, fail) {
    var confirmMessage = navigator.notification.confirm(
      message,
      onConfirm,
      '',
      [$filter('translate')('OK'), $filter('translate')('CANCEL')],
    );
    function onConfirm(index) {
      var condition = index === 1;
      observers.forEach(function(observer) {
        observer(condition);
      });
      return condition ? success() : fail();
    }
    return confirmMessage;
  }
}
//Outside of the factory

gService.observeNotify(function(condition){
  console.log(condition);
});

This way you can register functions, that will be called during the execution of the onConfirm function

Is this what you are expecting? I am not sure what is the problem. Can you explain more detail?

<!doctype html>
<html lang="en" ng-app="app">

<head>
  <meta charset="utf-8">
  <title>How AngularJS Works?</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
</head>

<body ng-controller="appCtrl">

  <p>Welcome to BooKart, we have collection of {{1 + ' Million'}} books.</p>
  <script>
    var app = angular.module('app', []);
    app.factory('gService', gService);

    function gService($filter, $window) {
      function confirmDialog(message, success, fail) {
        alert("called");
        var confirmMessage = navigator.notification.confirm(
          message,
          onConfirm,
          '', [$filter('translate')('OK'), $filter('translate')('CANCEL')]
        );

        function onConfirm(index) {
          return index === 1 ? success() : fail();
        }
        return confirmMessage;
      }
      return {
        confirmDialog:confirmDialog
      }
    }

    app.controller("appCtrl", function ($scope, gService) {
      $scope.callFun = function () {
        if (gService.confirmDialog("", "","").onConfirm) {

        }
      };
      $scope.callFun();
    });
  </script>


</body>

</html>

Convert onComfirm to a promise and do something after the promise is resolved.

function onConfirm(index) {
  return $q(function (resolve, reject) {
  index === 1 ? resolve(true) : reject(false);
  });
 }



  $scope.callFun = function () {
    gService.confirmDialog("", "","").onConfirm()
       .then(function(sucess) {
          successMethod();  
        }, function(error) {
           console.error('oh no');
        });

basically you are not returning (reference to the code you shared) anything from the function gService (implementation of your factory), since its a factory you have to return something. your inner function confirmDialog return an object, but the outer function gServive dosen't returns anything. The way you want to execute it, you have to return either confirmDialog callback and have to execute in the injecting end like

if(gServive(<..args...>).onConfirm())

and in case toy are returning a object then

return {confirmDialog: confirmDialog(...<args>...)}

and then in the injecting end

if(gService.confirmDialog.onConfirm)

Note: That your onConfirm is a function, by calling it, it will return something, so it has to ve invoked with (...), it is actually sounds like an event attacher function which will take a callback and fires on complete, but your code dosen't says that. in that case you can maintain a promise, and in onConfirm call take a callback as argument, and then pass it to then of that promise, and whenever you filled its time to confirm, just resolve that promise.

发布评论

评论列表(0)

  1. 暂无评论