Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AngularJS中的承诺管理来自控制器的服务回调?_Javascript_Angularjs - Fatal编程技术网

Javascript 使用AngularJS中的承诺管理来自控制器的服务回调?

Javascript 使用AngularJS中的承诺管理来自控制器的服务回调?,javascript,angularjs,Javascript,Angularjs,从控制器调用服务函数时,我必须管理回调。我的想法是将服务功能包装在一个承诺中,但是我不能直接从控制器引用服务功能。相反,我必须创建另一个函数来处理视图事件 function exampleSrv($q) { this.exampleFn = function() { var q = $q.defer(); // Do something q.resolve(); return q.promise; }; } function exampleCtr

从控制器调用服务函数时,我必须管理回调。我的想法是将服务功能包装在一个承诺中,但是我不能直接从控制器引用服务功能。相反,我必须创建另一个函数来处理视图事件

function exampleSrv($q) {

  this.exampleFn = function() {

    var q = $q.defer();
    // Do something
    q.resolve();

    return q.promise; 
  };
}

function exampleCtrl(exampleSrv) {

  this.exampleFn = exampleSrv.exampleFn;


/* This works but I want to avoid this if possible
  this.clickHandler = function() { 

    this.exampleFn()
        .then(function() {
          console.log('yay');
        })
  };
*/

/* And instead do something like this but as a reference not as a call
  this.exampleFn()
      .then(function() { 
        console.log('yay');
      })
*/
}
有没有更好的方法来做到这一点

例如:

简言之,,没有更好的方法。事实上,这是解决此类问题的明智方式。

事实上,你可以尝试这样的方法:(我遇到了plunker问题,否则会产生一个问题)

然后在HTML标记中,可以执行以下操作:

<!DOCTYPE html>
<html ng-app="example">

<head>
  <script data-require="angular.js@1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="exampleCtrl as example">
  <!-- bind value directly from service -->
  {{example.exampleFn}}
</body>

</html>

{{example.exampleFn}}
这样,您就不需要额外的控制器函数,可以将服务数据直接带到标记中。希望这就是你想要的。祝你好运

<!DOCTYPE html>
<html ng-app="example">

<head>
  <script data-require="angular.js@1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="exampleCtrl as example">
  <!-- bind value directly from service -->
  {{example.exampleFn}}
</body>

</html>