如何使一个功能工作?

时间:2014-12-22 16:37:29

标签: javascript angularjs

我正在尝试使用angular创建删除服务。

这是我的控制器:

app.controller('VoirMessagesController', function($scope, $rootScope, $routeParams, $location,$translate, userService, dataRefreshServices){
    $scope.messageToWatch = dataRefreshServices.getMessageToWatch();


    this.DeleteAMessage = function(){
        dataRefreshServices.SupprimerMessage($scope.messageToWatch).then(function(){
            $location.path('/messages'); // The problem is here
        });
    };


});

并且服务名为:

$this.SupprimerMessage = function(message){
        var retour = true;
        if(message != undefined)
        {
            $translate(['MESSAGES_MESSAGERIE_SUPPRIMER', 'BUTTON_CANCEL', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE']).then(function(translations)
            {
                    var modalOptions = {
                closeButtonText: translations.BUTTON_CANCEL,
                actionButtonText: translations.MESSAGES_MESSAGERIE_SUPPRIMER,
                headerText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE,
                bodyText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE
                };

                // displaying the modal box
                modalYesNoService.showModal({}, modalOptions).then(function (result) {              

                    var index = _.indexOf(listeMessages, _.find(listeMessages, function (_message) { return _message._id == message._id; }));
                    $this.SupprimerMessageFromServer(message).then(function(promise){
                        listeMessages[index]._id = 0;

                    });
                });
            });
        }
        return retour;
    };

我收到错误:

undefined is not a function
    at DeleteAMessage 

我知道我的函数没有返回任何承诺,但我不知道如何使这个工作,我只想让我的重定向与$ location.path完成只有当用户在我的模态窗口中点击是

我想在执行重定向之前添加一个“then”来等待用户的回答。

看起来我应该创建一个承诺,但无法想象我如何“创造”一个承诺。当我使用$ http.get时,我理解了承诺中的内容,但我不能(在没有数据预期之前,我只想知道用户何时点击了是)。

谢谢

3 个答案:

答案 0 :(得分:2)

你试图在布尔上拨打.then(),这当然不会起作用。 AngularJS documentation包含了使用$ q(其承诺的风格)的非常容易理解的示例。

来自文档:

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

答案 1 :(得分:1)

以下是您在脚本中引入承诺(使用$ q服务)的方法:

$this.SupprimerMessage = function(message){
        //var retour = true;//no more need
        var defer = $q.defer(); //inject $q into your service via dependency injection - here create a promise
        if(message != undefined)
        {
            $translate(['MESSAGES_MESSAGERIE_SUPPRIMER', 'BUTTON_CANCEL', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE']).then(function(translations)
            {
                    var modalOptions = {
                closeButtonText: translations.BUTTON_CANCEL,
                actionButtonText: translations.MESSAGES_MESSAGERIE_SUPPRIMER,
                headerText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE,
                bodyText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE
                };

                // displaying the modal box
                modalYesNoService.showModal({}, modalOptions).then(function (result) {              

                    var index = _.indexOf(listeMessages, _.find(listeMessages, function (_message) { return _message._id == message._id; }));
                    $this.SupprimerMessageFromServer(message).then(function(promise){
                        listeMessages[index]._id = 0;
                        defer.resolve({message:"Message corectly deleted"});
                    },function(){//this is the error callback if you used $http for SupprimerMessageFromServer
                        defer.reject({error:"Something went wrong while deleting message"});
                    });
                });
            });
        }
        else{
            defer.reject({error:"No message defined"});//this will go to the error callback of the promise
        }
        return defer.promise;//whatever return a promise on which you'll be able to call .then()
    };

答案 2 :(得分:1)

只需为回调添加参数(函数类型)

$this.SupprimerMessage = function(message, callback){
....
/* user pressed ok */
listeMessages[index]._id = 0;
callback();
....
}

$this.DeleteAMessage = function(){
    dataRefreshServices.SupprimerMessage($scope.messageToWatch, function() {
        $location.path('/messages');        
    });
};