gpt4 book ai didi

javascript - Angular : reusable function within a controller scope

转载 作者:行者123 更新时间:2023-11-28 18:39:10 25 4
gpt4 key购买 nike

我需要将一些代码注入(inject)到函数中,以防止 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 的方式创建一个可重用的函数呢?

最佳答案

也许像这样:

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 调用也提取到函数中。

关于javascript - Angular : reusable function within a controller scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36424284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com