1

The check() is called from the html, and the return value should be true/false.

ng-class="{'timeline-inverted: check(id)'}"

The $scope.server.get() get result(r) from the server script, and I need to return the $scope.result to the check() function.

Here is my code in angular:

$scope.check = _.memoize(function(userId) {
    $scope.server.get({
        action: 'checkif',
        userID: userId
    }).then(function successHandler(r) {
        $scope.result = r.data.result;
    });
    return $scope.result;   // $scope.result is undefined
});
lin
  • 17,956
  • 4
  • 59
  • 83

2 Answers2

1

Create a new Promise than you resolve once the HTTP call is successful.

$scope.check = _.memoize(function(userId) {
  return new Promise((resolve, reject) => {
    $scope.server.get({
      action: 'checkif',
      userID: userId
    }).then(function successHandler(r) {
      resolve(r.data.result);
    });
  });
});
  • `memoize` doesnt realy make sense here. It is currently caching the returning `promise` instead of the returned data. – lin Mar 15 '18 at 10:25
  • I have never used lodash, I'm just giving the usual way of returning the value. –  Mar 15 '18 at 10:27
0

First, using memoize is not a good deal here. memoized works perfectly fine as the argument has a primitive type. Since you call your API you cannot be sure that the same set of data is returned by the same userId & action params!

I don't know why your $http call is binded to an $scope. Maybe it better to place such stuff in a service. Finally your application could look like this nice structured app:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, user) {

   $scope.userData = null;

   user.get('checkif', 2).then(function (result) {
      $scope.userData = result.data.result;
   });
});


myApp.service('user', function () {
  this.get = function (action, userId) {
    return $http({
      url: 'http://your-api-endpoint/',
      method: 'GET',
      params: {
        action: action,
        userID: userId
      }
    });
  }
});
lin
  • 17,956
  • 4
  • 59
  • 83