如何比较这两个函数之间的值?

时间:2016-08-03 03:54:27

标签: javascript angularjs

我想比较这两个函数的variable值。不幸的是,我试图制作variables global,但我不断获得undefined

'use strict';

/**
 * @ngdoc function
 * @name dashyAppApp.controller:Dashy3Ctrl
 * @description
 * # Dashy3Ctrl
 * Controller of the dashyAppApp
 */

angular.module('dashyAppApp')
  .controller('Dashy3Ctrl', function ($rootScope, $scope, employees, $interval) {
   var _this = this;

  $scope.getData = function() { // getDATA function
    employees.getEmployees().then(function(response){
        _this.items = response.data;
        $scope.items = _this.items;

       callmecrazy(response.data);
    });

  }// End getDATA function
  $scope.getData();

  $scope.getDataB = function() {
  employees.getEmployees().then(function(response){
    _this.items = response.data;
     callmecrazier(response.data);
  });
 }
 $interval(function(){
 $scope.getDataB();
 }, 10000);

 function callmecrazier(response1){
   callmecrazierVal = response1.countries;
    return callmecrazierVal;
 }

 function callmecrazy(response){
  callmecrazyVal = response.countries;
  return callmecrazyVal;
 }

 if(!angular.equals(callmecrazierVal(), callmecrazyVal())) {
    //trigger some other function
  }
});

我想查看是否callmecrazierVal !== callmecrazyVal。这是我上面的完整controller代码。

if(callmecrazierVal !== callmecrazyVal){
  //trigger some other function
}

3 个答案:

答案 0 :(得分:2)

您应该从功能中返回一些内容。返回的值将被比较。

function callmecrazier(response1){
   var callmecrazierVal = response1.countries;
    return callmecrazierVal;
 }

 function callmecrazy(response){
  var callmecrazyVal = response.countries;
  return callmecrazyVal;
 }

然后将它们比作:

if(callmecrazierVal() !== callmecrazyVal()){
  //trigger some other function
}

答案 1 :(得分:1)

如果函数返回的值不是原语,则应该:

if(!angular.equals(callmecrazier(), callmecrazy()) {
   //trigger some other function
}

修改 我假设你想以10秒的间隔命中api并检查是否有任何变化,对吧? (否则,请澄清你想要达到的目标)。如果需要,您需要链接异步调用,然后进行比较,如下所示:

'use strict';

 /**
  * @ngdoc function
  * @name dashyAppApp.controller:Dashy3Ctrl
  * @description
  * # Dashy3Ctrl
  * Controller of the dashyAppApp
 */

angular.module('dashyAppApp')
 .controller('Dashy3Ctrl', function($rootScope, $scope, employees, $interval)            {
 var _this = this;

 $scope.getData = function() { // getDATA function
     return employees.getEmployees().then(function(response) {
       return response.data; 
     });

   } // End getDATA function


$scope.getData()
.then(function(data1){
   $scope.items = data1; 
   $interval(function() {
     $scope.getData()
     .then(function(data2){
        if (!angular.equals($scope.items, data1) {
          //trigger some other function
        }
     });
   }, 10000);

});

 });

答案 2 :(得分:0)

function callmecrazier(response1){
   var callmecrazierVal = response1.countries;
   return callmecrazierVal;
}

function callmecrazy(response){
   var callmecrazyVal = response.countries;
   return callmecrazyVal;
}

if(callmecrazier(response1) !== callmecrazy(response)){
   //Your code...........
}