why I get error: http.get is not a function - javascript

I have this code:
(function () {
"use strict";
angular.module("workPlan").controller("workPlanListController", ["workPlans",
"clients",
"inspectionAuthority",
"$http",
"config",
"workPlanServise",
workPlanListController]);
function workPlanListController(workPlans,
clients,
inspectionAuthority,
workPlanServise,
config,
$http) {
var self = this;
this.workPlanList = workPlans;
this.lookups = {
client: clients,
authority: inspectionAuthority
};
this.gridOptions = {
expandableRowTemplate: 'app/workPlan/templates/expandableRowTemplate.tmpl.html',
expandableRowHeight: 150,
enableColumnMenus: false,
enableSorting: true,
enableFiltering: false,
enableToopTip: true,
enableHorizontalScrollbar: 0,
onRegisterApi: function (gridApi) {
gridApi.expandable.on.rowExpandedStateChanged(null, function (row) {
if (row.isExpanded) {
row.entity.subGridOptions = {
columnDefs: [{ name: 'Authority', field: 'authName', cellTooltip: true },
{ name: '# Items, field: 'items2inspect', cellTooltip: true },
{ name: '% Inspected, field: 'percentage', cellTooltip: true }]
};
$http.get(config.baseUrl + "api/workPlan/").success(function (result) {
row.entity.subGridOptions.data = result.data;
});
}
});
}
}
this.gridOptions.columnDefs = [
{ name: 'client, field: 'clientName', cellTooltip: true, headerTooltip: true },
{ name: 'sites', field: 'siteNumbers', cellTooltip: true, headerTooltip: true },
{ name: 'checkedSites', field: 'siteNumbersInspected', cellTooltip: true, headerTooltip: true }];
this.gridOptions.data = self.workPlanList;
}
})();
When I try expand row I get on this row:
$http.get
Error : $http.get in not a function.
Any idea why I get error?

You shouldn't change the dependency sequence while using dependencies in the controller function.
Code
angular.module("workPlan").controller("workPlanListController", ["workPlans",
"clients",
"inspectionAuthority",
"$http",
"config",
"workPlanServise",
workPlanListController
]);
function workPlanListController(workPlans,
clients,
inspectionAuthority,
$http, //<-- $http should be here, instead of placing it at the end.
config,
workPlanServise
) {
Same SO Answer here

Related

unable to access $scope in angular formly

please find my controller file..
(function () {
var app = angular.module('myApp',['formly','formlyBootstrap'])
app.run(function(formlyConfig) {
formlyConfig.setType({
name: 'custom',
templateUrl: 'custom.html'
});
});
app.factory('jsonService', function jsonService($http){
return {
getJSON: getJSON
};
function getJSON(abc) {
console.log("Inside" + abc);
return $http.get('readJson.php?abc='+abc);
}
});
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
selectHobbies(abc);
}
}
}]
})
})();
selecthobbies.js file.
function selectHobbies(abc)
{
console.log("here " + abc);
$scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
}
I am unable to access $scope in my selecthobbies.js file.
is there any way i can call onChange function which is not in a same file..???
I am getting the error $scope is not defined..
index.html file
<html>
<head>
<script src="api-check.js"></script>
<script src="angular.js"></script>
<script src="formly.js"></script>
<script src="jquery.min.js"></script>
<script src="angular-formly-templates-bootstrap.js"></script>
<script src="mycontroller.js"></script>
<script src="selecthobbies.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
</head>
<body ng-app="myApp" ng-controller="MyController">
<formly-form model="user" fields="userFields"></formly-form>
<formly-form model="fillSecDropDown" fields="fillDropDown"></formly-form>
</body>
</html>
Since you asked for an external file, you can change your function like this :
function selectHobbies(scope, abc)
{
console.log("here " + abc);
scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
return scope;
}
and in your controller :
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
$scope = selectHobbies($scope, abc);
}
}
}]
})
but that is not pretty at all, just don't do that if you can.
If you need this, then something is wrong with your function, please just refactor it in a better way.
EDIT -> You can do it with a service, in a much better way :
(function() {
'use strict';
angular
.module('yourApp')
.factory('yourService', yourServiceFactory);
function yourServiceFactory() {
var service = {
get: get
}
return service;
function get(abc) {
return {
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
}
})();
And then in your controller :
app.controller('MyController', function ($scope, yourService) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
$scope.fillSecDropDown.push(yourService.get(abc));
}
}
}]
})
Move your selecthobbies.js file. into your controller, would be something like this:
(function () {
var app = angular.module('myApp',['formly','formlyBootstrap'])
app.run(function(formlyConfig) {
formlyConfig.setType({
name: 'custom',
templateUrl: 'custom.html'
});
});
app.factory('jsonService', function jsonService($http){
return {
getJSON: getJSON
};
function getJSON(abc) {
console.log("Inside" + abc);
return $http.get('readJson.php?abc='+abc);
}
});
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
selectHobbies(abc);
}
}
}];
$scope.selectHobbies = function(abc){
console.log("here " + abc);
$scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
}
})
})();

Iterate JSON array in angular controller

I am trying to iterate through the array in Json and display the values in front end. I have given my code but I could not figure out where exactly I am wrong. I am not able to retrieve the values(startDate, endDate) inside the array and show them at front end.
JSON
"reportTypeObligationTypes": [{
"reportTypeId": null,
"consolidationScopeId": 4009,
"startDate": "2014-01-01",
"endDate": "9999-12-31",
"frequencyCode": "Q",
"reportTypeLabel": null,
"reportTypeCode": null,
"consolidationScopeCode": "C",
"frequencyLabel": "Quarterly"
}]
Angular controller
xxxApp.controller('reportListController', function ($scope, $http, $location, $routeParams) {
var service_url = "/mdmservice/services/reportTypeEntities/" + $routeParams.id;
$http.get(service_url).success(
function (data, status, headers, config) {
$scope.reportTypeEntities = data;
angular.forEach($scope.reportTypeEntities, function (item) {
console.log(item.reportTypeObligationTypes);
})
});
$scope.gridOptions = {
paginationPageSizes: [25, 50, 100, 200, 300, 400, 500, 1000],
paginationPageSize: 25,
};
$scope.gridOptions.data = 'reportTypeEntities';
$scope.gridOptions.enableFiltering = true;
$scope.gridOptions.enableGridMenu = true;
$scope.gridOptions.fastWatch = true;
$scope.gridOptions.columnDefs = [{
name: "entityName",
width: "35%",
cellTemplate: '<div style="margin-left: 5px;">' + ' {{row.entity.entityName}}' + '</div>'
}, {
name: "entityCode",
width: "15%"
}, {
name: "codeType"
}, {
name: "Entity Type",
field: "entityType.entityTypeName"
}, {
name: "reportingId"
}, {
name: "Country",
field: "country.countryName"
}, {
name: "startDate",
field: "reportTypeObligationTypes.startDate"
}, {
name: "endDate",
field: "reportTypeObligationTypes.endDate"
}, {
name: "consolidationScopeCode",
field: "reportTypeObligationTypes.consolidationScopeCode"
}, {
name: "frequencyLabel",
field: "reportTypeObligationTypes.frequencyLabel"
}, {
name: "Delete",
cellTemplate: '<div style="margin-left: 5px;">' + ' Delete' + '</div>',
enableFiltering: false,
enableSorting: false
}];
})
HTML Page - Angular UI grid
<div ng-app="xxxApp" ng-controller="reportListController">
<p class="heading">Entities with Reporting Obligation</p>
<!-- Entities list data table using - 'ui-grid' module -->
<div ui-grid="gridOptions" class="myGrid" ui-grid-pagination
ui-grid-selection ui-grid-resize-columns ui-grid-move-columns
ui-grid-cellNav ui-grid-exporter></div>
In your controller, assign $scope.reportTypeObligationTypes = [{JSON}];
Your tag or directive ex:
<div ng-repeat="item in reportTypeObligationTypes">
<div>{{item.startDate}}</div>
<div>{{item.endDate}}</div>
</div>
'item' will represent each JSON object in the array and you can use item.(property). To reference each object property.
EDIT:TRY:
$scope.gridOptions = {
data: $scope.myData,
columnDefs: [
{ name: 'field1', displayName: 'pretty display name' },
{ name: 'field2', visible: false }
]
};

Collapse all nodes initially Infragistics IgTree

I am using the following Infragistics component for viewing hierarchical data. http://www.igniteui.com/tree/drag-and-drop-single-tree
I have initialized the tree view like below to see all the nodes of the tree expanded initially. Can someone please suggest me if I am missing any option to display all nodes collapsed initially?
$("#tree").igTree({
checkboxMode: "off",
singleBranchExpand: true,
nodeClick: function (evt, ui) {
if (ui.node.data.Folder == "") {
var agreements = [];
var entry = [];
entry.push(ui.node.data.AgreementNbr);
entry.push(ui.node.data.ExternalDescription);
entry.push(ui.node.data.Description);
entry.push(ui.node.data.EffDate);
entry.push(ui.node.data.ExpDate);
entry.push(ui.node.data.ReleaseStatus);
agreements.push(entry);
$('#example').DataTable({
responsive: true,
columns: [
{ title: "Agreement Number" },
{ title: "External Description" },
{ title: "Description" },
{ title: "Effective Date." },
{ title: "Expiry Date" },
{ title: "Release Status" }
],
data: agreements,
destroy: true,
processing: true,
});
}
else {
var output = ui.node.data.Folder.map(function (obj) {
var a = [obj.AgreementNbr, obj.ExternalDescription, obj.Description, obj.EffDate, obj.ExpDate, obj.ReleaseStatus];
return Object.keys(a).map(function (key) {
return a[key];
});
});
console.log(output);
$('#example').DataTable({
responsive: true,
columns: [
{ title: "Agreement Number" },
{ title: "External Description"},
{ title: "Description"},
{ title: "Effective Date"},
{ title: "Expiry Date"},
{ title: "Release Status"}
],
data : output,
destroy: true
});
}
},
dataSource: files,
dataSourceType: "json",
initialExpandDepth: 0,
pathSeparator: ".",
bindings: {
textKey: "Text",
valueKey: "Value",
imageUrlKey: "ImageUrl",
childDataProperty: "Folder",
Description: "Description"
},
// Enable Drag-and-drop feature
dragAndDrop: false
});
Use the initialExpandDepth option
initialExpandDepth : -1
You have that option set to 0.
If you set the initialExpandDepth to -1, all nodes should display collapsed initially.
You can see infragistics.com for more information.

Type Error when trying to preserve filter state - Kendo UI Grid

I'm working with Kendo UI's Grid and attempting to add some code which preserves the grid's filter/grouping/etc by way of a cookie. It works in the example, but not at all in my code.
Example: http://www.kendoui.com/code-library/web/grid/preserve-grid-state-in-a-cookie.aspx
My Code: http://jsfiddle.net/PwajE/
For whatever reason (I'm sure it's a simple one) I keep getting type errors. Two hours later... here I am.
As always, any help is appreciated.
#RRfive
<script>
var data = [{"name":"John Smith","email":"test#test.com","permission":"admin","costRate":"60","dt":"2013-02-02 10:26:29","memberID":"M0000001"},{"name":"Test Simple","email":"test#jones.com","permission":"user","costRate":"40","dt":"2013-02-02 00:00:00","memberID":"M0000002"}];
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: data,
//transport: {
// read: "assets/data/data.users.php",
//},
schema: {
data: function(result) {
return result.data || result;
},
total: function(result) {
var data = this.data(result);
return data ? data.length : 0;
},
model:{
id:"memberID",
fields:{
dt:{ type:"date" },
costRate:{ type:"number" }
}
}
},
pageSize: 10,
},
sortable: {
mode: "single",
allowUnsort: true,
},
pageable: {
input: true,
numeric: false
},
reorderable: true,
resizable: true,
filterable: {
extra:false,
operators: {
string:{
contains: "Contains",
}
}
},
columnMenu: false,
groupable: true,
dataBound: function(e){
var grid = this;
var dataSource = this.dataSource;
var state = kendo.stringify({
page: dataSource.page(),
pageSize: dataSource.pageSize(),
sort: dataSource.sort(),
group: dataSource.group(),
filter: dataSource.filter()
});
$.cookie("employeesState",state);
if($.cookie('empRows')){
$.each(JSON.parse($.cookie('empRows')),function(){
var item = dataSource.get(this);
var row = grid.tbody.find('[data-uid='+item.uid+']');
row.addClass('k-state-selected');
})
}
},
change:function(){
var grid = this;
var ids = grid.select().map(function(){
return grid.dataItem($(this)).Id
}).toArray();
$.cookie('empRows',JSON.stringify(ids));
},
columns: [
{ field: "name", title:"Name" },
{ field: "email", title:"Email/Username" },
{ field: "costRate", title:"Cost Rate (p/hr)", template: '#= kendo.toString(costRate, "c") #', },
{ field: "permission", title:"Permission", template: "#= (permission == 'admin') ? 'Administrator' : 'User' #" },
{ field: "dt", title:"Registered", template: '#= kendo.toString(dt,"d-M-yyyy") #' },
{ field: "memberID", title:" ", width: "83px", filterable: false, sortable: false, template: '<a class="k-button k-button-icontext k-grid-edit" href="manage_admin.php?form=editMember&ID=#= kendo.toString(memberID, "n2")#"><span class=\"k-icon k-edit\"></span>Edit</a>'},
]
});
var state = JSON.parse($.cookie("employeesState"));
if(state){
if(state.filter){
parseFilterDates(state.filter, grid.dataSource.options.schema.model.fields);
}
grid.dataSource.query(state);
}
else{
grid.dataSource.read();
}
});
function parseFilterDates(filter, fields){
if(filter.filters){
for(var i = 0; i < filter.filters.length; i++){
parseFilterDates(filter.filters[i], fields);
}
}
else{
if(fields[filter.field].type == "date"){
filter.value = kendo.parseDate(filter.value);
}
}
}
</script>
If you debug that fiddle you would see that the following line throws the error:
grid.dataSource.query(state);
The reason for this is that grid is not an instance of Kendo Grid but the div elemen with id='grid'. The fix is simple - initialize the grid variable prior to using it:
var grid = $("#grid").data('kendoGrid');
grid.dataSource.query(state);

Unable to access data from Rally wsapidatastore

When I create a WsapiDataStore, store.data.items and store.data.keys return empty arrays although I am able to see the keys and items when I do console.log(store.data)
store = Ext.create('Rally.data.WsapiDataStore', {
model: 'Defect',
context: {
project: '/project/xxxxxx'
},
autoLoad: true,
fetch: ['Rank', 'FormattedID', 'Name']
});
Output of console.log(store.data):
constructor {items: Array[0], map: Object, keys: Array[0], length: 0, allowFunctions: falseā€¦}
allowFunctions: false
events: Object
generation: 8
getKey: function (record) {
hasListeners: HasListeners
items: Array[7]
keys: Array[7]
length: 7
map: Object
sorters: constructor
__proto__: TemplateClass
Notice how the first line says "items: Array[0]" and "keys: Array[0]" but when expanded it says "items: Array[7]" and "keys: Array[7]". I'm also able to see the 7 records when I expand further.
Everything works as expected when I add a load listener and access the data from the listener function (but I don't want to do that)
I think the best way is to process the data via two Rally.data.WsapiDataStore's. You'll need to chain the listeners for the two stores together in order to properly handle the asynchronous loads. Here's an example that illustrates the process:
<!DOCTYPE html>
<html>
<head>
<title>MultipleModelExample</title>
<script type="text/javascript" src="https://rally1.rallydev.com/apps/2.0p5/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function() {
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
// Combined Story/Defect Records
dataRecords: null,
launch: function() {
//Write app code here
this.dataRecords = [];
Rally.data.ModelFactory.getModels({
types: ['HierarchicalRequirement','Defect'],
scope: this,
success: function(models) {
this.myModels = models;
this.storyStore = Ext.create('Rally.data.WsapiDataStore', {
model: models.HierarchicalRequirement,
fetch: true,
autoLoad: true,
remoteSort: true,
sorters: [
{ property: 'FormattedID', direction: 'Asc' }
],
listeners: {
load: this._processStories,
scope: this
}
});
}
});
},
_processStories: function(store, records, successful, opts) {
var storyRecords = [];
Ext.Array.each(records, function(record) {
//Perform custom actions with the data here
//Calculations, etc.
storyRecords.push({
FormattedID: record.get('FormattedID'),
Name: record.get('Name'),
Description: record.get('Description')
});
});
this.dataRecords = storyRecords;
this.defectStore = Ext.create('Rally.data.WsapiDataStore', {
model: this.myModels.Defect,
fetch: true,
autoLoad: true,
remoteSort: true,
sorters: [
{ property: 'FormattedID', direction: 'Asc' }
],
listeners: {
load: this._processDefects,
scope: this
}
});
},
_processDefects: function(store, records, successful, opts) {
var defectRecords = [];
Ext.Array.each(records, function(record) {
//Perform custom actions with the data here
//Calculations, etc.
defectRecords.push({
FormattedID: record.get('FormattedID'),
Name: record.get('Name'),
Description: record.get('Description')
});
});
var combinedRecords = defectRecords.concat(this.dataRecords);
this.add({
xtype: 'rallygrid',
store: Ext.create('Rally.data.custom.Store', {
data: combinedRecords,
pageSize: 25
}),
columnCfgs: [
{
text: 'FormattedID', dataIndex: 'FormattedID'
},
{
text: 'Name', dataIndex: 'Name', flex: 1
},
{
text: 'Description', dataIndex: 'Description', flex: 1
}
]
});
}
});
Rally.launchApp('CustomApp', {
name: 'MultipleModelExample'
});
});
</script>
<style type="text/css">
.app {
/* Add app styles here */
}
</style>
</head>
<body></body>
</html>

Categories