有几段相同代码,我想封装成一个函数,请问改怎么封装?
//====第一段代码======
var cookies = document.cookie;
var start = cookies.indexOf("authData=");
if(start == -1){
console.log("The cookie not found");
}
start = cookies.indexOf("=", start) + 1;
var end = cookies.indexOf(";", start);
if(end == -1){
end = cookies.length;
}
var authData = unescape(cookies.substring(start, end));
if(authData == null){
console.log("The cookie not found");
}
else{
var json = JSON.parse(authData);
for(var i=0; i< json.data.length;i++){
if(json.data[i].partentId == $routeParams.addAdminId){
if(json.data[i].actionName == "提交"){
$scope.submitAddAdmin = true;
}
}
}
}
//====第二段代码============
var cookies = document.cookie;
var start = cookies.indexOf("authData=");
if(start == -1){
console.log("The cookie not found");
}
start = cookies.indexOf("=", start) + 1;
var end = cookies.indexOf(";", start);
if(end == -1){
end = cookies.length;
}
var authData = unescape(cookies.substring(start, end));
if(authData == null){
console.log("The cookie not found");
}
else{
var json = JSON.parse(authData);
for(var i=0; i< json.data.length;i++){
if(json.data[i].partentId == $routeParams.roleAuthListId){
if(json.data[i].actionName == "编辑"){
$scope.editRoles = true;
}
if(json.data[i].actionName == "删除"){
$scope.delRoles = true;
}
}
}
}
每段代码只有else 里面的 for循环里面的代码不一样,请问这种怎么封装成一个函数?
PHP中文网2017-04-10 17:27:35
Angular中一般封装成service
app.factory('getAuthData', function() {
return function(cb) {
var cookies = document.cookie;
var start = cookies.indexOf("authData=");
if (start == -1) {
console.log("The cookie not found");
}
start = cookies.indexOf("=", start) + 1;
var end = cookies.indexOf(";", start);
if (end == -1) {
end = cookies.length;
}
var authData = unescape(cookies.substring(start, end));
if (authData == null) {
console.log("The cookie not found");
} else {
var json = JSON.parse(authData);
cb(json)
}
}
})
在controller里注入就可以使用了
app.controller('myController',['getAuthData',function(getAuthData){
getAuthData(function(json){
console.log(json);
})
}])
迷茫2017-04-10 17:27:35
只封装获取cookie中authData的数据部分
function getAuthData(){
var cookies = document.cookie;
var start = cookies.indexOf("authData=");
if(start == -1){
console.log("The cookie not found");
return {data:[]}
}
start = cookies.indexOf("=", start) + 1;
var end = cookies.indexOf(";", start);
if(end == -1){
end = cookies.length;
}
var authData = unescape(cookies.substring(start, end));
if(authData == null){
console.log("The cookie not found");
return {data:[]}
}
else{
return JSON.parse(authData);
}
}
var json= getAuthData();
for(var i=0; i< json.data.length;i++){
if(json.data[i].partentId == $routeParams.addAdminId){
if(json.data[i].actionName == "提交"){
$scope.submitAddAdmin = true;
}
}
}
for(var i=0; i< json.data.length;i++){
if(json.data[i].partentId == $routeParams.roleAuthListId){
if(json.data[i].actionName == "编辑"){
$scope.editRoles = true;
}
if(json.data[i].actionName == "删除"){
$scope.delRoles = true;
}
}
}