Angular:控制器范围内的可重用函数

时间:2016-04-05 10:49:20

标签: javascript angularjs

我需要将一些代码注入函数中,以防止DRY。这是我的代码示例。

angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
  var self = this;
  self.encrypt = function() {
    $http.post('/encrypt',
             {'crypt': {'text': self.plain, 'shift':self.rot}})
    .then(function(response) {
      self.encrypted = response.data.encrypted;
      self.plain = '';
    // reusable function goes here
    // var frequencyArr = response.data.frequency;
    // var frequencyArrLength = frequencyArr.length;
    // if (frequencyArrLength) self.cryptChart = [frequencyArr];
    });
  };
  self.decrypt = function() {
    $http.post('/decrypt',
           {'crypt': {'text': self.encrypted, 'shift':self.rot}})
    .then(function(response) {
      self.plain = response.data.plain;
      self.encrypted = '';
      // and here 
      // the stuff to become a function
      var frequencyArr = response.data.frequency;
      var frequencyArrLength = frequencyArr.length;
      if (frequencyArrLength) self.cryptChart = [frequencyArr]; 
    });
  };
  // ...
}])

那么如何打包3行并以Angular方式创建可重用的函数?

1 个答案:

答案 0 :(得分:3)

也许是这样的:

angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
  var self = this;

  function cryption(decrypt, callBack) {
    $http.post(
      decrypt ? '/decrypt' : '/encrypt', 
      {crypt: {text: decrypt ? self.encrypted : self.plain, shift: self.rot }})
    .then(callBack);
  }

  function cryptChart(response) {
    var frequencyArr = response.data.frequency;
    var frequencyArrLength = frequencyArr.length;
    if (frequencyArrLength) // can be simplyfied to response.data.frequency.length
      self.cryptChart = [frequencyArr];
  }

  self.encrypt = cryption(false, function(response) {
      self.encrypted = response.data.encrypted;
      self.plain = '';

      cryptChart(response);    
  });
  self.decrypt = cryption(true, function(response) {
      self.plain = response.data.plain;
      self.encrypted = '';

      cryptChart(response);
  });  
  // ...
}])

我进一步将共享的$ http.post调用解压缩到函数中。