How to share code in angular js (concept of code resuability in angular js? - angularjs

i am new to angular js and i want to share and make certain codes reusable. i have tried to do that using services and factory. But i am getting error.
'use strict';
angular.module('myApp.ctrls')
.controller('Ctrl_HubStockOnHandMode', function($http, $scope, reportService) {
$scope.HubStockOnHandModeGridOptions = {
dataSource: {
type: "jsonp",
transport: {
read: function(e) {
reportService.WebAPI('abc/BIUMo', {
EnvironmentCode:'JMVH',
OrderBy: getOrderBy(e.data.sort)
}).then(function (d) {
$scope.data = d;
e.success(d.Data);
});
}
},
serverPaging: true,
serverSorting: true
},
height:config.GridHeight,
scrollable:true,
sortable: {
mode: "single",
allowUnsort: true
},
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to",
contains: "Contains"
}
}
},
pageable: false,
columns: [
{
field: "RowNumber"
,title: "No."
,width: "50px"
,sortable:false
,filterable: false
},
{
field: 'ItemCTSH'
,title:'Item'
,template: "<div kendo-tooltip title='#= ItemCT #' > #= ItemCTSH # </div>"
,filterable: {
ui: itemFilter
}
},
]
};
}
//Get Item List
$http.get('http://webapi.dashboard.hcmisonline.org/api/OID_WebApi/IssuedItemList')
.success(function (data) {
$scope.items = data.Data;
});
function itemFilter(element) {
element.kendoAutoComplete({
dataSource: $scope.items
});
}
}
});
I want to reuse the functions like the Get item. i have other pages/grids that use exactly this code, except changing the environment code
how to i solve this issue?
thanks

Related

KendoUI Grid for AngularJS binding error from asp.net mvc controller. Success is not a function error

I attempt to do simple task using KendoUI grid for AngularJS in asp.new mvc application. It is binding data to grid from mvc controller.
asp.net mvc controller method:
public ActionResult GetCdcReport()
{
var testJson =
#"{ProductID:'1',ProductName:'Chai',UnitPrice:'18',UnitsInStock:'39',Discontinued:'false'}";
var json = JObject.Parse(testJson);
return new JSONNetResult(json);
}
angularjs service function:
function getImportResultReport() {
return httpPost('getCdcReport');
}
code from component for data binding:
$scope.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true,
dataSource: {
pageSize: 5,
transport: {
read: function (e) {
dataservice.getImportResultReport().
success(function (data) {
e.success(data);
}).
error(function (data, status) {
alert('something went wrong');
console.log(status);
});
}
}
}
};
I see that server method is called but in console i get following client error:
dataservice.getImportResultReport(...).success is not a function
In similar question i read that:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead.
i replace binding code on:
$scope.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true,
dataSource: {
pageSize: 5,
transport: {
read: function (e) {
dataservice.getImportResultReport().
then(function (data) {
return data;
});
}
}
}
};
After that I don't receive this error but grid stay without data.
Also i attempted do it like:
vm.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true
};
$scope.mainGridOptions.DataSource = dataservice.getImportResultReport();
it is also not work.
What i'm doing wrong?
It is example from telerik site. If in binding logic replase dataservice.getImportResultReport() on $http.jsonp('URL FROM EXAMPLE') then it is work.

Kendo grid not showing data only on the initial load, but works fine when stepping through with breakpoints

The problem I'm having is exactly what I said in the title. When I step through my application in the debugger it properly sets everything that needs to be set, but when I just let it go through on its own, it never loads data on the initial attempt, but if i go back and click the same thing again, or any thing else that has to send data to this grid, it will forever work. Even if I go to a page that empties everything in the grid and then go back to one that shows data again.
To me it sounds like a timing issue, but using $timeout() before the data calls doesn't seem to be working. And I set up a broadcast that should only be called after all the data is pulled in and set, and only then should it go to the code for the kendo grid and start painting it on the page.
Like I said stepping through this code line by line on the initial load of the page, it works exactly as it should and pulls in all data that it needs, but letting it just run without me doing that, it never does.
here is hopefully enough code to go off of.
Here is the code for my grid:
$scope.$on('loadRxHistoryGrids', function () {
console.log('user id of ' + pServ.patientId.get());
$scope.activeHistoryGrid = {
pageable: {
pageSizes: [5, 10, 15, 20],
},
dataSource: new kendo.data.DataSource({
type: 'aspnetmvc-ajax',
contentType: "application/json; charset=utf-8",
transport: {
read: {
url: function () {
var x = pServ.patientId.get();
return "api/rx/ActiveRxHistory/" + pServ.patientId.get();
},
dataType: "json",
type: "POST"
},
},
pageSize: 5,
schema: {
model: {
fields: {
rxId: { type: "number" },
refillsLeft: { type: "number" },
shortName: { type: "string" },
unitsRemaining: { type: "number" },
dispenseRefillQuantity: { type: "number" },
description: { type: "string" },
shipDate: { type: "date" }
},
},
data: function (data) {
if (data != undefined) {
$scope.ActiveHistoryCount = data.length;
return data;
} else { return []; }
},
total: function (data) {
return data.length;
},
},
}),
serverPaging: true,
serverSorting: true,
serverFiltering: true,
columns: [
{ hidden: true, field: "rxId"},
{ field: "shortName", title: "DRUG NAME"},
{ field: "refillsLeft", title: "REFILLS LEFT", width: "16%", template: '#= (refillsLeft == null) ? " " : kendo.toString( refillsLeft, "n0")#', attributes: { style: "text-align:left" } },// template: '<div style="text-align:left">#= ((unitsRemaining == null) || (dispenseRefillQuantity == null)) ? " " : kendo.toString(unitsRemaining / dispenseRefillQuantity, "n5")#</div>' },
{ field: "description", title: "STATUS", width: "14%", template: '<div style="text-align:left">#= (description == null) ? " " : description#</div>' },
{ field: "shipDate", title: "SHIPPED DATE", width: "15%", template: '#= (shipDate == null) ? " " : kendo.toString(kendo.parseDate(shipDate), "MM/dd/yyyy") #' }
],
groupable: false,
scrollable: true,
selectable: true,
resizeable: true,
sortable: true,
}
Here is the other code where the broadcast is being sent:
$scope.$on('loadPatientProfileData', function () {
//A lot of data gets and sets are being done here for other things on the
//page, all data is being set in the grid datasource itself
setTimeout(function () {
$rootScope.$broadcast('patientProfile-DataPullFinish');
$rootScope.$broadcast('loadRxHistoryGrids');
}, 100);
});

Struggling to write a Jasmine testcase for AngularJS

The below code is my controller logic and I want to create a Jasmine test case for it. With $inject I am getting problem how to mock or use the services used in $inject and write a Jasmine test case for below AngularJS controller logic.
(function () {
'use strict';
var controllerId = 'user';
angular.module('app').controller(controllerId, user);
user.$inject = ['$rootScope', 'userService', 'common'];
function user($rootScope, $userService, common) {
var vm = this;
vm.users = [];
vm.sorting = {
column: "UpdatedDate",
order: 0
};
vm.gridHeaders = [
{ title: "UserName", visible: true, sort: true, name: 'UserName', filter: true, type: 'string' },
{ title: "First Name", visible: true, sort: true, name: 'FirstName', filter: true, type: 'string' },
{ title: "Middle Name", visible: true, sort: true, name: 'MiddleName', filter: true, type: 'string' },
{ title: "Last Name", visible: true, sort: true, name: 'LastName', filter: true, type: 'string' },
{ title: "Email Address", visible: true, sort: true, name: 'EmailID', filter: true, type: 'string' },
{ title: "Phone Number", visible: true, sort: true, name: 'PhoneNumber', filter: true, type: 'string' },
{ title: "Mobile Number", visible: true, sort: true, name: 'MobileNumber', filter: true, type: 'string' },
{ title: "City", visible: true, sort: true, name: 'City', filter: true, type: 'string' },
{ title: "Role", visible: true, sort: true, name: 'RoleID', filter: true, type: 'int' },
{ title: "Address", visible: true, sort: true, name: 'Address', filter: true, type: 'string' },
{ title: "UserType", visible: true, sort: true, name: 'UserType', filter: true, type: 'int' },
{ title: "RoleName", visible: true, sort: true, name: 'RoleName', filter: true, type: 'string' }
];
vm.editUser = function (value) {
if (value > 0) {
var request = [{
"PageNumber": vm.pagination.currentPage,
"PageSize": vm.pagination.pageSize,
"SortColumn": vm.sorting.column,
"SortOrder": vm.sorting.order,
"Query": "UserID=" + value
}];
$userService.sendUserID(request);
}
}
vm.loadUserSearchDetails = function () {
//common.showSpinngMan();
var pageConstants = common.preparePageConstants();
vm.pageDropDown = pageConstants.pageDropDown;
vm.pagination = pageConstants.pagination;
loadGrid();
};
vm.loadPageData = function (scenario) {
vm.pagination.currentPage = common.setPagination(scenario, vm.pagination)
loadGrid();
};
//Load grid
var loadGrid = function (data) {
var request = [{
"PageNumber": vm.pagination.currentPage,
"PageSize": vm.pagination.pageSize,
"SortColumn": vm.sorting.column,
"SortOrder": vm.sorting.order,
"Query": ""
// Filters: vm.filterPanel.savedFilter
}];
$rootScope.loading = true;
$userService.getUserDetails(request).then(function (result) {
debugger;
if (!!result) {
vm.users = result.SearchUsers;
vm.pagination.totalRecords = vm.users.length;
vm.pagination.totalPages = Math.ceil(vm.pagination.totalRecords / vm.pagination.pageSize);
}
}).catch(function (result) {
console.log("error load grid");
//$location.path("/error");
}).finally(function () {
$rootScope.loading = false;
})
};
return vm;
}
})();
for the above controller code i have written jasmine testcase by removing injected service userservice and common.js
the new part consists :
//user.$inject = ['$rootScope', 'userService', 'common']; //line removed
function user($rootScope) { // , $userService, common params removed
var vm = this;
vm.users = [];
commented the code relating to $userservice and written jasmine testcase like below and it's working fine.. my question is how write when i inject the other dependencies i.e. 'userservice' 'common'
describe("A suite", function () {
beforeEach(module('app'));
var $controller;
var mockServiceDepedency;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
it("testing 5", function () {
var $rootScope = {};
var controller = $controller('user', { $rootScope: $rootScope });
expect(controller.users).not.toBeNull();
expect(controller.users).toEqual([]);
expect(controller.sorting.column).toEqual("UpdatedDate");
expect(controller.sorting.order).toEqual(0);
expect(controller.gridHeaders[0]).toEqual({ title: "UserName", visible: true, sort: true, name: 'UserName', filter: true, type: 'string' });
expect(controller.pageDropDown).not.toBeNull();
expect(controller.pageDropDown).not.toBeNull();
expect(controller.loadUserSearchDetails.pageConstants).not.toBeNull();
});
});

I want to read a array value inside factory in angularjs

I am trying to read value in array in factory but I am unable to do so. I am using ng-grid and when I click on one row I get selecteditems list which I pass in another controller where I call a factory service in which I pass that as a parameter but that parameter in the factory stays as array and when I read it using index it shows blank.
My code is as below -
myNgApp.controller('MyGrid', ['$scope', function ($scope) {
$scope.mySelections = [];
$scope.mySelItems = [];
$scope.myData = [{ Reference: 12, Customer: "fff", Title: "sd", Task: "Enter Details", Received: "Today", Due: "01/09/2014" },
{ Reference: 7899, Customer: "eee", Title: "dsd", Task: "Enter Details", Received: "Yesterday", Due: "05/09/2014" }];
$scope.gridOptions = {
data: 'myData',
checkboxHeaderTemplate: '<input class="ngSelectionHeader" type="checkbox" ng-model="allSelected" ng-change="toggleSelectAll(allSelected)"/>',
selectWithCheckboxOnly: true,
showSelectionCheckbox: true,
selectedItems: $scope.mySelections,
multiSelect: true,
columnDefs: [{ field: 'Reference', displayName: 'Reference', width: '*' }, { field: 'Customer', displayName: 'Customer', width: '**' }, { field: 'Title', displayName: 'Title', width: '***' }, { field: 'Task', displayName: 'Task', width: '***' }, { field: 'Received', displayName: 'Received', width: '**' }, { field: 'Due', displayName: 'Due', width: '**' }],
showGroupPanel: true,
enableCellSelection: false,
enableRowSelection: true,
enableCellEditOnFocus: false,
enablePinning: true,
showColumnMenu: true,
showFilter: true,
enableColumnResize: true,
enableColumnReordering: true,
maintainColumnRatios: true,
afterSelectionChange: function () {
angular.forEach($scope.mySelections, function (item) {
if ($scope.mySelItems.length == 0) {
$scope.mySelItems.push(item.Title)
}
else {
$scope.mySelItems[0] = item.Title
}
});
}
};
}]);
myNgApp.factory('myPreviewDataService', function () {
return function (x) {
var arr = [x, "Apple", "Banana", "Orange"];
return arr
};
});
myNgApp.factory('myPreviewTplService', function () {
return function () {
return '<div><div class="ngPreviewItems" ng-repeat="item in items">{{item}}</div></div>';
};
});
myNgApp.directive('showPreview', function ($compile) {
return {
scope: true,
link: function (scope, element, attrs) {
var el;
attrs.$observe('template', function (tpl) {
if (angular.isDefined(tpl)) {
// compile the provided template against the current scope
el = $compile(tpl)(scope);
// stupid way of emptying the element
element.html("");
// add the template content
element.append(el);
}
});
}
};
});
myNgApp.controller('myPreviewController', function ($scope, myPreviewDataService, myPreviewTplService) {
//$scope.showContent = function () {
$scope.items = myPreviewDataService($scope.mySelItems);
$scope.template = myPreviewTplService();
//};
});
here $scope.mySelItems is from ng grid controller that gets updated when we select a checkbox.
What I get is an array but I am unable to read its content, when I display the array as it is it gets displayed like ["test"] but when I try to read it x[0] in myPreviewDataService factory or by $scope.mySelItems[0] in myPreviewController then I get blank. I am not able to figure out why this is happening
I was able to solve it. In myPreviewDataService factory I changed the array elements from string to array
var arr = [x, "Apple", "Banana", "Orange"];
changed to
var arr = [x, ["Apple"], ["Banana"], ["Orange"]];
and in myPreviewTplService factory I changed {{item}} to {{item[0]}}
it worked.
P.S I think we can also use ng switch based on condition in myPreviewTplService factory based on the type of item, I tried to do it but I was not able to do so and worked with my earlier solution.

Kendo UI Grid foreign key column using Angular directives

I'm trying to make a Kendo Grid that has 2 foreign key columns using the Angular directives for Kendo. I am able to get one to work, but not the other (independent of each other). If I comment one out the other will work and vice versa, but either way only one will work. Abbreviated sample code is below.
invoicesController.js
app.controller('invoicesController', [
'$scope', '$rootScope', 'config', 'dataFactory', function($scope, $rootScope, config, dataFactory) {
$rootScope.title = 'Invoices';
$scope.filterCustomers = [];
$scope.filterStatuses = [];
$scope.invoiceGrid = null;
var _refreshCustomers = function () {
dataFactory.get(_.string.format('{0}customers', config.apiUrl)).success(function (result) {
$scope.filterCustomers = _.map(result, function (cust, key) {
return {
text: cust.name,
value: cust.id
}
});
});
};
var _refreshStatuses = function() {
dataFactory.get(_.string.format('{0}invoicestatuses', config.apiUrl)).success(function(result) {
$scope.filterStatuses = _.map(result.data, function(status, key) {
return {
text: status.name,
value: status.id
}
});
_initializeGrid();
});
};
var _refreshData = function () {
_refreshCustomers();
_refreshStatuses();
};
_refreshData();
var _initializeGrid = function() {
$scope.invoiceGrid = {
dataSource: {
transport: {
read: _.string.format('{0}invoices', config.apiUrl),
},
schema: {
data: 'data'
},
pageSize: 15,
sort: { field: 'invoiceDate', dir: 'asc' }
},
columns: [
{ title: 'Subject', field: 'subject', type: 'string', width: '30%'},
{ title: 'Number', field: 'number', width: '12%' },
{ title: 'Customer', field: 'customer.id', values: $scope.filterCustomers, width: '15%' },
{ title: 'Status', field: 'status.id', values: $scope.filterStatuses, width: '14%' },
{ title: 'Total', field: 'invoiceTotal', type: 'number', format: '{0:c2}', width: '10%' },
{
title: 'Updated', field: 'updatedOn', type: 'date', format: '{0:d}', width: '19%',
template: '#=lastUpdated#'
}
],
scrollable: false,
sortable: true,
filterable: true,
pageable: true
};
}
}
]);
dataFactory.js (GET method)
return $http({
url: url,
method: 'GET',
data: data,
});
list.html
<div data-kendo-grid data-k-ng-delay="invoiceGrid" data-k-options="invoiceGrid" class="top"></div>
I was able to get this to work using route resolve.
Basically, when you're defining your routes, you can set resolvers. In this case, I'm resolving customers and statuses which you will also see as arguments on the projectsController
app.js (routing config)
// Projects
$routeProvider.when('/projects', {
templateUrl: '/app/views/projects/list.html',
controller: 'projectsController',
resolve: {
customers: ['customerService', function (customerService) {
return customerService.getCustomers();
}],
statuses: ['projectService', function (projectService) {
return projectService.getStatuses();
}]
}
});
projectsController.js (abbreviated)
app.controller('projectsController', [
'$scope', '$rootScope', 'config', 'customers', 'statuses', function($scope, $rootScope, config, customers, statuses) {
// Set the options from the injected statuses (from the route resolver)
$scope.statusOptions = _.map(statuses.data.data, function(status) {
return { value: status.id, text: status.name }
});
....
// Kendo grid column definition
columns: [
{ title: 'Status', field: 'status.id', values: $scope.statusOptions, width: '15%' },
]
}]);

Resources