Controlling service callbacks from controller using promises in AngularJS?

I need to manage a callback when calling a service function from a controller. My idea is to secure the functionality of the service, but then I cannot directly reference the service function from the controller. Instead, I need to create another function to handle view events.

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');
      })
*/
}

      

Is there a better way to do this?

Example: http://plnkr.co/edit/jg5yoC?p=info

+3


source to share


2 answers


In short, no , there is no better approach to this. This is actually the recommended way to deal with such problems.



+1


source


Actually, you can try something like this: (I have plunger problems, otherwise it would create one)

// Example Service
function exampleSrv($q) {

  this.exampleFn = function() {

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

    return q.promise.then(function() {

      return {
        "data": "12345"
      };
    });
  };
}

// Example Controller

function exampleCtrl(exampleSrv) {

  var ctrl = this;
  exampleSrv.exampleFn().then(function(data){
     ctrl.exampleFn = data;
  });

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

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

  /* And instead do something like this 
  this.exampleFn()
      .then(function() { 
        console.log('yay');
      })
*/
}

angular.module('example', [])
  .service('exampleSrv', exampleSrv)
  .controller('exampleCtrl', exampleCtrl);

      

Then, in your HTML markup, you can do this:



<!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>

      

This way you don't need an additional controller function and can take overhead directly to your markup. Hope this is what you were looking for. Good luck.

0


source







All Articles