DreamWalker
DreamWalker

Reputation: 1387

Angular: reusable function within a controller scope

I need to inject some piece of code into a function, to prevent DRY. Here is an example of my code.

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]; 
    });
  };
  // ...
}])

So how do I pack that 3 lines and make a reusable function in Angular way?

Upvotes: 0

Views: 49

Answers (1)

Miroslav Jonas
Miroslav Jonas

Reputation: 6627

Maybe like this:

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);
  });  
  // ...
}])

I went bit further and extracted the shared $http.post call into function as well.

Upvotes: 3

Related Questions