使用函数作为控制器中的参数

时间:2015-07-02 21:33:47

标签: javascript angularjs

好的,我有一个控制器,我需要使用一个函数作为参数

angular.module('myCtrl', function($scope) {
 $scope.$on('lines:deselectLine', function(ev, slip) {
  _.each($scope.lineItems, function(lineItem) {
    _.each(lineItem, function(lineLeague) {
      _.each(lineLeague, function(line) {
        _.each(line.rows, function(row) {              
          if (row.nss + '' === slip.nss) {
            var line = slip.line;
            if (line === row.spread.line + '') {
              row.spreadSelected = false;
            }
            if (line === row.total.line + '') {
              row.totalSelected = false;
            }
            if (line === row.moneyLineId + '') {
              row.moneyLineSelected = false;
            }
          }
        });
      });
    });
  });
 });
});

这是完整的功能,但我需要在函数中取消这部分

          if (row.nss + '' === slip.nss) {
            var line = slip.line;
            if (line === row.spread.line + '') {
              row.spreadSelected = false;
            }
            if (line === row.total.line + '') {
              row.totalSelected = false;
            }
            if (line === row.moneyLineId + '') {
              row.moneyLineSelected = false;
            }
          }

所以最后我需要这样的东西

angular.module('myCtrl', function($scope) {
 $scope.$on('lines:deselectLine', function(ev, slip) {
  _.each($scope.lineItems, function(lineItem) {
    _.each(lineItem, function(lineLeague) {
      _.each(lineLeague, function(line) {
        _.each(line.rows, function(row, iWillBeFunctionParam) {              
           //SOMETHING NEW WILL HAPPEN HERE
        });
      });
    });
  });
 });

 $scope.iWillBeFunctionParam = function(slip) {
   if (row.nss + '' === slip.nss) {
      var line = slip.line;
      if (line === row.spread.line + '') {
         row.spreadSelected = false;
      }
      if (line === row.total.line + '') {
         row.totalSelected = false;
      }
      if (line === row.moneyLineId + '') {
         row.moneyLineSelected = false;
      }
    }
  };

});

请注意$scope.$on$emit ...

那么,我应该怎么做才能将新功能用作Param?

1 个答案:

答案 0 :(得分:1)

看起来你不需要将一个函数作为参数传递给控制器​​,所以你的标题有点令人困惑。

似乎你想在最里面的_.each中调用一些函数。也许我误解了你的意图,但是我没有看到任何需要将iWillBeFunctionParam作为参数传递给任何地方的地方。

所以,你有以下几点 - 无论是否在控制器中,不相关 - 概念上说:

var lines = [[], [], []]; // array of arrays

$scope.$on("foo", function(ev, slip){
  _.each(lines, function(line){
    _.each(line.rows, function(row){
      doSomethingWith(slip, line, row);
    })
  })
})

然后您可以相应地定义doSomethingWith函数:

function doSomethingWith(slip, line, row){
   // etc...
}