Angularjs Service未获取控制器中的值

时间:2015-02-17 13:04:44

标签: angularjs angularjs-service angularjs-factory

我有一个angularjs服务,可以获得验证结果,并根据它处理页面。

****************************** My Controller ****************
angular.module('angularApp').controller('angularCtrl', function($scope,validateFactory){

    function getValidationResult(){
        return validateFactory.getValidationResult().then(function(data){
        return data;
    });
  }

     $scope.submission = function submitForm(){
         $scope.form.email.$error.validateEmail = getValidationResult();

        if(validateEmail){
        /* Based on validateEmail value there are some code needs to be executed*/
        }    
     }
});

**************************** My Validation Service ***********************


angular.module('angularApp').factory('validateFactory',function($http,$log){
return {
    getValidationResult : getValidationResult
};

function getValidationResult(){
    return $http.get('data/email-exists.json').then(getValidationCompleted).catch(getValidationFailed);

    function getValidationCompleted(response){
        return response.data;
    }

    function getValidationFailed(error){
        console.log("There is an error in email validation");
    }
};

我没有获取validateEmail变量的json数据,而是获得了promise并且在if循环之后解析了。我尝试使用$ q.defer()但得到相同的结果,或者我可能会遗漏几行,因为我是角度js的新手。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您遗漏了一个小细节getValidationResult会返回一个承诺,因此您需要更改:

    $scope.form.email.$error.validateEmail = getValidationResult();

    if(validateEmail){
    /* Based on validateEmail value there are some code needs to be executed*/
    }

要:

    getValidationResult().then(function(data) {
      if(data){
        /* Based on validateEmail value there are some code needs to be executed*/
        $scope.form.email.$error.validateEmail = data;
      } 
    });