有几段相同代码,我想封装成一个函数,请问改怎么封装?
//====第一段代码======
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循环里面的代码不一样,请问这种怎么封装成一个函数?
Angular中一般封装成service
在controller里注入就可以使用了
只封装获取cookie中authData的数据部分