【问题标题】:Use $resource return value inside custom parser在自定义解析器中使用 $resource 返回值
【发布时间】:2015-09-16 21:05:56
【问题描述】:

我正在研究一个角度指令,它实现了一个解析器,通过点击服务器来验证当前输入,服务器返回一个 true/false 状态,我必须使用它:

  1. 使模型无效
  2. 模型值无效时设置为“未定义”

我已经通过使用$setValidity完成了上面的1.但是在2.因为我需要使用服务器返回的状态给$parser函数,但是由于我必须等待服务器响应,所以返回语句内部回调没有用。

app.directive('testDir', ['$resource',function($resource){

return{
  restrict:'A',
  require:'ngModel',
  scope:{},
  link:function(scope,element, attr,ngModel){
    ngModel.$parsers.push(function (inputValue) {

    var req=$resource('data.json');
    var modelval='123';
    req.get({},function(result){
      ngModel.$setValidity('id',result.status);
      //ngModel.$setViewValue(result.name);
      console.log(result.name);
      modelval=result.status?inputValue:undefined;
      return modelval; // this doesn't work
     });
    return modelval; // executes before reading the JSON so always '123'
    });
  }
};

我觉得我缺少一些非常基本的 JS,因为我们无法从函数内部返回到外部函数,但无法找到解决方案。

非常感谢任何帮助!

plunker

【问题讨论】:

    标签: javascript angularjs angular-resource angular-directive


    【解决方案1】:

    $resource 是一个工厂,很像$http,它可以返回一个$promise。因此,当您返回变量 modelval 时,您将在返回更新此变量的承诺之前返回它。您应该执行以下操作:

     var req=$resource('data.json');
     var modelval='123';
     req.get({}).$promise.then(function(result){
       ngModel.$setValidity('id',result.status);
       //ngModel.$setViewValue(result.name);
       console.log(result.name);
       modelval=result.status?inputValue:undefined;
       return modelval; // this will update if the request is a success
     }, function(error){
        //error handling should go here
    });
    return modelval; // this will still execute before reading the JSON so will always return '123'
    });
    

    如果你想在其他地方使用 promise 的返回,你应该考虑使用$q。这是另一项服务,可让您推迟已解决或已拒绝的承诺,以便在其他地方使用。

    【讨论】:

    • 您的解决方案似乎不起作用,虽然回调得到正确执行,但返回值不会更新模型,即使result.status 为假,我期待最终模型值为“未定义”而不是“123”。我已经用你的解决方案更新了 plunk。请看一看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2019-05-24
    • 2016-01-13
    • 2020-09-21
    相关资源
    最近更新 更多