We are constantly getting false positive issues from our JavaScript plugins regarding the function complexity and function length rules.
The reason is that we have functions that are written inside function and the outer functions get the issues.
I understand that technically the complexity looks at everything,
but isn't there a way of getting the plugin to look only at the functions themselves?
(other than marking it as false positive)
Server version 4.5.6
JavaScript plugin version 2.9
There is a complexity issue of rule "javascript:FunctionComplexity" (complexity=25) for the redeployCtrl function.
This is the code, as you can see the actual complexity is from the inner functions.
is there a way around this other than marking the issue as false positive (and losing the complexity issue for the inner functions) or writing a custom rule?
thanks.
function redeployCtrl($scope, utilService, $filter, $location, generalSettings, $uibModalInstance, $uibModal, $timeout,scheme) {
$scope.openStart = openStart;
$scope.isSubmitable = isSubmitable;
$scope.ipCheckbox = ipCheckbox;
$scope.deploy = deploy;
$scope.init = init;
$scope.cancel = cancel;
function init() {
$scope.scheme = scheme;
$scope.loading = 'false';
$scope.envSchemes = [];
$scope.isPermanent = false;
$scope.permanent = {};
$scope.scheme.Scheme.Description = null;
$scope.scheme.Scheme.ExpTime = null;
var max = generalSettings.CalendarEndDate;
$scope.maxDate = new Date();
$scope.maxDate.setMonth($scope.maxDate.getMonth() + max);
$scope.minDate = new Date();
$scope.minDate = $scope.minDate.setDate($scope.minDate.getDate() + generalSettings.MinExpirationDate);
$scope.dateOptions = {
'year-format': 'yyyy',
'starting-day': 1
};
utilService.post(generalSettings.serverPath + 'envscheme/ListSupervisors/', { })
.then(function (data) {
$scope.supervisors = data;
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to retrieve data", "img_error");
});
utilService.post(generalSettings.serverPath + 'envscheme/ListPermReasons/', { })
.then(function (data) {
$scope.permReasons = data;
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to retrieve data", "img_error");
});
}
function openStart() {
$timeout(function () {
$scope.startOpened = true;
});
}
function deploy(scheme, isPermanent) {
if (isPermanent) {
scheme.Scheme.ExpTime = '01/01/9999';
scheme.Scheme.ApprovedBy = $scope.permanent.approvedBy;
if ($scope.permanent.mainReason === 'Other') {
scheme.Scheme.Reason = $scope.permanent.customReason;
} else {
scheme.Scheme.Reason = $scope.permanent.mainReason;
}
} else {
$scope.scheme.Scheme.ExpTime = utilService.getFormattedDate($scope.scheme.Scheme.ExpTime);
}
$scope.loading = 'true';
utilService.post(generalSettings.serverPath + 'envscheme/ReCreateEnv', scheme)
.then(function (data) {
if (data.Success) {
utilService.alertAmpm("Deploy started successfuly", "Info", "img_information");
$location.path("/MyEnvironments");
}
else {
utilService.alertAmpm(data.Reason, "Failed to Re-Deploy", "img_error");
$scope.loading = 'false';
}
if (data.Reason.indexOf("Session was not found") < -1) {
sessionStorage.clear();
$scope.loading = 'false';
}
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to Re-Deploy", "img_error");
$scope.loading = 'false';
});
}
function isSubmitable(invalid, modules) {
if (!invalid) {
for (var i = 0; i < modules.length; i++) {
if (modules[i].ipchkBox) {
if (!modules[i].OS.Parameters.IP) {
return true;
}
}
}
return false;
}
return true;
}
function ipCheckbox(checkBox, name) {
if (!checkBox) {
var name1 = "ipText" + name;
$('[name=' + name1 + ']').val('');
$scope.scheme.Scheme.modules[name].OS.Parameters = new Object();
}
}
function cancel() {
$uibModalInstance.dismiss('cancel');
}
Roy.
These rules force the coding with less nested functions. They ignore some cases like IIFE or practices accepted in some frameworks (AMD, Angular). But that's obviously is not your case.
So if you think that this coding practice is not for you, the only thing you can do is to disable the rules (and may create custom rules counting only lines you want).
Related
I'm using angular.js with C# web service and I need to increment ng-repeat item by item to show to the user as the data is updated, to do this I'm trying to use $http.get within loop for refresh data in each item. But its not working
for (var i = 0; i < conditions.length; i++) {
var configFullAsset = {
params: {
Field: Field,
SAM_ConnectionString: SAM_ConnectionString,
TreeElemId: conditions[i][0],
ConditionDate: conditions[i][1]
}
};
$http.get('application.asmx/getExtFullAssetHealth', configFullAsset)
.success(function (responseExt) {
console.log("Element: ", i);
if (i == 0)
{
$scope.showData = responseExt;
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
}
else
$scope.showData = $scope.showData.concat(responseExt);
//console.log("Data item: ", $scope.showData[i].Tag);
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
})
.catch(function (err) {
console.log("Error get object: ", err);
})
.finally(function () {
// Hide loading spinner whether our call succeeded or failed.
//$scope.loading = false;
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
console.log($scope.fullData);
});
}
The main problem into your code is the fallowing: you use i as index in the success method but is not what you expected because the loop is over until your first success will be called.
You can build the requests like this in the first phase, is much easier to read:
function buildRequests() {
return conditions.map(function(condition) {
var configFullAsset = {
params: {
Field: Field,
SAM_ConnectionString: SAM_ConnectionString,
TreeElemId: condition[0],
ConditionDate: condition[1]
}
};
return $http.get('application.asmx/getExtFullAssetHealth', configFullAsset);
});
}
Than you can handle all the requests like this:
function handleRequests() {
var requests = buildRequests();
$q.all(requests)
.then(handleRequests)
.catch(function(error) {
console.log(error);
})
.finally(function() {
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
});
}
Than to iterate over each result to make the changes:
function handleResults(results) {
results.forEach(function(response, i) {
console.log("Element: ", i);
if (i == 0)
{
$scope.showData = response;
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
}
else
$scope.showData = $scope.showData.concat(response);
//console.log("Data item: ", $scope.showData[i].Tag);
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
});
}
Do not forget to inject $q as dependency injection.
I have many different controllers throughout this project and all of them are declared the same way. This one now isn't getting called/giving an error and I have no clue why. I've looked through it and it all looks right to me.
I think it's probably some syntax error I'm not seeing. If its something else please tell me. I'm trying to learn angular and everything helps. Also if you need anything else just tell me.
I've made sure its not that the app.js name got changed and been looking for missing syntax but can't find anything.
https://docs.angularjs.org/error/ng/areq?p0=companyDepartmentController&p1=not%20a%20function,%20got%20undefined
company-department-controller.js
app.controller('companyDepartmentController', ['$scope', '$timeout', 'companyService', function ($scope, $timeout, companyService) {
/**
* Create/Manage Company Departments & Shifts
*
*/
// INITIALIZE VARIABLES *********************************************************************************
var vm = this;
vm.Departments = [];
vm.activeDepartment = {}
vm.departmentBeforeEdit = {};
vm.activeShift = {};
vm.OffsetString = "";
vm.SaveDepartmentSuccessMessage = null;
vm.SaveDepartmentErrorMessage = null;
// STARTUP **********************************************************************************************
(vm.GetDepartments = function () {
companyService.GetDepartmentsWithShiftInformation().success(function (data) {
console.log('hi');
for (i = 0; i < data.length; i++) {
console.log(data[i])
}
vm.Departments = data;
// for now we are limiting this to 1
vm.activeDepartment = vm.Departments[0];
vm.setTimeZoneOffsets(vm.activeDepartment);
});
})();
// move to global location? handle this better?
(vm.findLocalOffsetString = function () {
console.log('hi1');
vm.OffsetString = moment(new Date()).format('ZZ');
})();
// $BROADCAST/$ON EVENTS ********************************************************************************
// EVENTS ***********************************************************************************************
vm.saveDepartment = function (department) {
// new
if (department.DepartmentID === 0 || typeof department.DepartmentID === 'undefined') {
}
// update
else {
companyService.UpdateDepartmentHeader(department).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
department.InEdit = false
});
}
};
vm.editDepartment = function (department) {
vm.activeDepartment = department;
vm.departmentBeforeEdit = angular.copy(vm.activeDepartment);
vm.activeDepartment.InEdit = true;
};
vm.cancelDepartmentEdit = function (department) {
for (var i = 0; i < vm.Departments.length; i++) {
if (department.DepartmentID === vm.Departments[i].DepartmentID) {
vm.Departments[i] = vm.departmentBeforeEdit;
vm.departmentBeforeEdit = {};
vm.activeDepartment = vm.Departments[i];
break;
};
};
};
vm.addShift = function () {
if (!vm.activeDepartment) return;
vm.activeShift = {
DepartmentID: vm.activeDepartment.DepartmentID,
StartTime: new Date(),
LocalStartTime: new Date(new Date() + vm.OffsetString)
};
vm.activeShift.StartTime.setSeconds(0);
vm.activeShift.LocalStartTime.setSeconds(0);
};
vm.deleteShift = function (shift) {
if (!shift) return;
if (confirm("Are you sure you want to delete the shift: " + shift.Name + "?")) {
companyService.DeleteShift(shift).success(function () {
angular.forEach(vm.activeDepartment.Shifts, function (c, i) {
if (c.ShiftID === shift.ShiftID) {
vm.activeDepartment.Shifts.splice(i, 1);
};
});
});
};
};
vm.setTimeZoneOffsets = function (department) {
if (!department || !department.Shifts || department.Shifts.length === 0) return;
for (var i = 0; i < department.Shifts.length; i++) {
department.Shifts[i].LocalStartTime = new Date(department.Shifts[i].StartTime + vm.OffsetString);
department.Shifts[i].EndTime = moment(department.Shifts[i].StartTime).add(department.Shifts[i].Duration, 'hours').toDate()
};
};
var fixTimezoneOnSave = function (shift) {
shift.StartTime = new Date(shift.LocalStartTime).toLocaleString();
};
vm.setActiveShift = function (shift) {
if (!shift) return;
vm.activeShift = angular.copy(shift);
};
vm.saveShift = function (shift) {
fixTimezoneOnSave(shift);
// new shift
if (shift.ShiftID === 0 || typeof shift.ShiftID === 'undefined') {
companyService.AddShift(shift).success(function (data) {
shift.ShiftID = data;
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
// updating existing
else {
companyService.UpdateShift(shift).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
}
var getUpdatedShiftsAndInfo = function () {
companyService.DepartmentAndShiftInformation(vm.activeDepartment.DepartmentID).success(function (data) {
vm.activeDepartment.DepartmentShiftInformation = data.DepartmentShiftInformation;
vm.activeDepartment.Shifts = data.Shifts;
vm.setTimeZoneOffsets(vm.activeDepartment);
});
};
var resetDepartmentMessage = function () {
// clear error/success message if they have values still
if (vm.SaveDepartmentSuccessMessage != null) {
$timeout(function () { vm.SaveDepartmentSuccessMessage = null; }, 2000);
}
if (vm.SaveDepartmentErrorMessage != null) {
$timeout(function () { vm.SaveDepartmentErrorMessage = null; }, 2000);
}
};
// create controller object in console if we have logging turned on
if (spectrum.LoggingEnabled) {
spectrum.logController(vm);
};
}]);
_CompanyDepartment.cshtml
<div class="container-fluid" data-ng-controller="companyDepartmentController as cd">
</div>
#section scripts {
#Scripts.Render("~/bundles/companyDepartments")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/angularjs")
}
app.js
var app = angular.module('app', ['angularFileUpload', 'ngSanitize', 'ui.mask', 'ui.select', 'ui.bootstrap', 'ui.bootstrap.tpls', 'angular.filter', 'smart-table', 'colorpicker.module'])
.config(function ($httpProvider) {
//make delete type json to facilitate passing object
//to our generic method.
$httpProvider.defaults.headers["delete"] = {
'Content-Type': 'application/json;charset=utf-8'
};
});
Outside of a naming issue with the controller(which I can't see), I would imagine your issue dealing with the company-department-controller.js not being loaded.
In setting up your angular project, I would suggest that you follow this angular styleguide. It has been very helpful to me in creating a well structured project.
I have a subroutine I want to use in my controller. In the case or working with data, a new record blanks fields, as would a screen clear, and after some other processes, I would like to clear the editable fields on the view.
Controller:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
function ClearMemberStruture()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);
ClearMemberStructure() is used to reset the common structure fields and the Edit flag which controls showing information on the screen. When I run this code, I always get a
ReferenceError: ClearMemberStructure is not defined
How can I share this common function in my controller in AngularJS?
If I add a Factory, I can achieve this using calls to the factory:
angular.module('MyApp').factory("MemberRecord", function() {
var Member = {
Key: "",
Name: "",
Points: ""
};
return {
Clear: function() {
Member.Key = "";
Member.Name = "";
Member.Points = "";
return Member;
}
};
}
);
And then in the controller:
$scope.member = MemberRecord.Clear();
Is there a way to do the simply function style code sharing, as I do want this to be handled as a private function, but cannot get it to recognize the function in the controller.
var ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
is your solution to declare ClearMemberStruture without breaking your whole code.
I use a separate file with factories to share code between controllers.
App.factory('CommonServices', function ($http) {
return {
createComment: function($api_key, $post_id, $comment) {
var comment_data = {
content: $comment
};
return $http({
url: '/api/v1/posts/' + $post_id + '/comments',
method: "POST",
headers: { 'X-API-TOKEN': $api_key },
params: comment_data,
data: ''
})
}
});
Then in a controller you can access the common functions like:
$scope.saveComment = function($post_id) {
CommonServices.createComment($scope.api_key, $post_id, $scope.comment.text)
.then(function(_data) {
var index = $scope.feed_items.filter(function (post) { return post.id == $post_id });
index[0].comments.unshift(_data.data);
$scope.showComment = false;
});
}
I prefer to use factory for Member and encapsulate method there. But you can try the easier way:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
var that = this;
that.ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
that.ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);
I have two angularjs function in my dataContext object that receive data from an webapi as you can see below
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId,
['common', datacontext]);
function datacontext(common) {
var service = {
getAllTagsByHttp: getAllTagsByHttp,
getBlogPostsByHttp: getBlogPostsByHttp,
getAllUserPicByHttp: getAllUserPicByHttp
};
return service;
function getAllTagsByHttp() {
return common.$http.get('/api/TagApi/alltags');
}
function getBlogPostsByHttp() {
return common.$http.get('/api/BlogPostApi/AllBlogPosts');
}
function getAllUserPicByHttp() {
return common.$http.get('/api/BlogPostApi/AllUserPic');
}
}})();
I have an angularjs controller that call these api functions from the datacontext to receive information to display back to the user. The getblogPost function is called first because the next function need's the data from this to operate on.the second function does a comparison on the first function's data to display back the img source to the user. The problem i am having is that it takes quite a few seconds for the second function to receive the data and an complete its operation. The amount of data being send back is a few records.Is there any improvements that can be made to controller or data Context object to reduce the time or improve the code?
(function () {
'use strict';
var controllerId = 'search';
angular
.module('app')
.controller(controllerId, ['common','datacontext', search]);
function search(common, datacontext) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.title = 'search';
vm.picData = [];
activate();
function activate() {
var promises = [getBlogPosts(), getUserPicData(), getUserPicUrl()];
common.activateController(promises, controllerId)
.then(function () { log('Search View'); });
}
function getBlogPosts() {
datacontext.getBlogPostsByHttp().then(function (response) {
vm.data = response.data;
});
}
function getUserPicData() {
datacontext.getAllUserPicByHttp().then(function (response) {
vm.picData = response.data;
for (var i = 0; vm.data.length > i; i++) {
for (var x = 0; vm.picData.length > x; x++) {
if (vm.data[i].UserName == vm.picData[x].UserName) {
vm.data[i].PictureUrl = vm.picData[x].PictureUrl;
// console.log(vm.data[i].PictureUrl);
break;
}
}
}
});
}
function getUserPicUrl(username) {
getUserPicData();
for (var i = 0; vm.picData.length < i; i++) {
if (vm.picData[i].UserName === username) {
return vm.picData[i].PictureUrl;
}
}
return "not found";
}
}})();
I'm working on an extension for Google Chrome and I ran into the following situation:
I'm trying to get all the existing tabs from all the opened windows in the same instance of Google Chrome. I manage to get them and construct an array of objects that contain the relevant data for me.
When I look at the constructed array using console.log (which is saved for future use also) I can see the collection of objects, but I can't reference them (when I try I get undefined).
I tried to save the array outside my object in a container, but nothing changes.
Any idea why the reference to the objects go away when I try to look them up? Thanks.
Here is the code:
(function(window){
//defining a namespace
var example = {
bmarksmaster: (function() {
var bmarksmaster = function() {
return new bmarksmaster.fn.init();
}
bmarksmaster.fn = bmarksmaster.prototype = {
debug: false,
tabs: [],
constructor: bmarksmaster,
init: function() {
return this;
},
windowParser: function(ctx, filter) {
var local = ctx;
var filter = filter;
return function(wObj) {
if((wObj !== null) && (wObj !== undefined)) {
for(var idx in wObj) {
var cw = wObj[idx];
if((cw.tabs !== null) && (cw.tabs !== undefined)) {
var cwtabs = cw.tabs;
for(var tabIdx in cwtabs) {
local.tabs.push(filter(tabIdx, cwtabs[tabIdx]));
}
}
}
}
};
},
getTabs: function() {
var returnData = [];
chrome.windows.getAll(
{
"populate": true
}, this.windowParser(this, function(i, e) {
var data = {};
if(!e.incognito) {
data["title"] = e.title;
data['url'] = e.url;
data['favicon'] = e.favIconUrl || "";
}
return data;
}));
return this.tabs;
},
getTab: function(callback) {
this.getTabs();
for (var tabIdx in this.tabs) {
if(callback(tabIdx, this.tabs[tabIdx])) {
return this.tabs[tabIdx];
}
}
},
getTabsData: function(callback) {
var data = [];
var tabs = [];
tabs = this.getTabs();
console.log(this.tabs[0]);
for (var tabIdx in tabs) {
console.log(tabs[tabIdx]);
var tabData = callback(tabIdx, tabs[tabIdx]);
if(tabData) {
data.push(tabData);
}
}
return data;
},
setDebug: function() {
this.debug = true;
},
resetDebug: function() {
this.debug = false;
}
};
bmarksmaster.fn.init.prototype = bmarksmaster.fn;
return bmarksmaster;
})()
};
window.example = example;
})(window);
//end of bmarksmaster.js file
console.log(example.bmarksmaster().getTabs()); //this works, I can see the array
console.log(example.bmarksmaster().getTabs()[0]); //this doesn't work, I get undefined, never mind the shortcut
I think the logic in your code is wrong. It is a bit convoluted and hard to follow. I would recommend rewriting it a bit to be simpler. Something like this might help get you started. It collects all the windows, putts all the tabs into the tabs var.
var tabs = [];
chrome.windows.getAll({ populate: true}, function(windows) {
var localTabs = windows.reduce(function(a, b){
return a.tabs.concat(b.tabs);
});
tabs = localTabs.filter(function(element){
return !element.incognito;
});
})