Angular Datatables Not Applying Correctly - angularjs

Here is my html code:
<div ng-controller="withAjaxCtrl">
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table>
</div>
Here is my controller:
(function () {
var manageBackOrdersController = function ($scope, $http, $routeParams) {
$http({
url: '/Profiles/firstJson',
method: "GET",
params: {}
}).success(function (data) {
var JSON = data;
$scope.data = JSON;
});
}
manageBackOrdersController.$inject = ['$scope', '$http', '$routeParams'];
angular.module('customersApp')
.controller('manageOrdersController', manageOrdersController);
angular.module('datatablesSampleApp', ['datatables'])
.controller('withAjaxCtrl', function ($scope, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtOptions = DTOptionsBuilder.fromSource('scope.data')
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('Customer').withTitle('Customer')
];
});
}());
When I run my page I get an error saying "Error: [ng:areq] Argument 'withAjaxCtrl' is not a function, got undefined". My data is found stored in $scope.data.

Respectfully, Sameer's answer is incorrect. It took me two long arduoous days but I found the solution.
What you must keep in mind are 2 concerns:
Use DTOptionsBuilder.fromFnPromise, and
Have your promise inside your factory.
This is the correct solution:
'use strict';
WithResponsiveCtrl.$inject = ['DTOptionsBuilder', 'DTColumnBuilder', 'simpleFactory'];
angular.module('showcase.withResponsive', [])
.controller('WithResponsiveCtrl', WithResponsiveCtrl);
function WithResponsiveCtrl(DTOptionsBuilder, DTColumnBuilder, simpleFactory) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
return simpleFactory.getData(); }).withPaginationType('full_numbers')
// Active Responsive plugin
.withOption('responsive', true);
vm.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
// .notVisible() does not work in this case. Use .withClass('none') instead
DTColumnBuilder.newColumn('lastName').withTitle('Last name').withClass('none')
]; }
simpleFactory.$inject = ['$http', '$q', '$log'];
angular.module('showcase.withResponsive').factory('simpleFactory', simpleFactory);
function simpleFactory($http, $q, $log) {
return {
getData: function () {
var deferred = $q.defer();
$http.get('api/data.json')
.success(function (data) {
deferred.resolve(data);
}).error(function (msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
}
} };

Related

How do I add $http.get to controller?

In this plunker: http://plnkr.co/edit/OZa7rvWLQuRHJGiJ8dBL?p=preview
I'm having difficulty adding $http.get to the controller so that the page runs.
In app.js --
I have this code:
angular.module('example-app', ['hc.marked', 'hljs'])
.config(['markedProvider', 'hljsServiceProvider', function(markedProvider, hljsServiceProvider) {
// marked config
markedProvider.setOptions({
gfm: true,
tables: true,
sanitize: true,
highlight: function (code, lang) {
if (lang) {
return hljs.highlight(lang, code, true).value;
} else {
return hljs.highlightAuto(code).value;
}
}
});
}])
.controller("MainController", ["$rootScope", "$scope", "marked", function MarkdownController($rootScope, $scope, marked, $http) {
}]);
How to add this $http.get so that the plunker continues to work properly??
$http.get('http://beta.json-generator.com/api/json/get/VyD_JWT1Q')
.then(function (res) {
$scope.todos = res.data.todo;
$scope.events = res.data.event;
$scope.aboutlongs = res.data.aboutlong;
$scope.mainpoints = res.data.mainpoint;
$scope.tags = res.data.tag;
$scope.galleries = res.data.gallery;
$scope.menus = res.data;
$scope.socials = res.data.social;
});
I've tried this, but it breaks:
angular.module('example-app', ['hc.marked', 'hljs'])
.config(['markedProvider', 'hljsServiceProvider', function(markedProvider, hljsServiceProvider) {
// marked config
markedProvider.setOptions({
gfm: true,
tables: true,
sanitize: true,
highlight: function (code, lang) {
if (lang) {
return hljs.highlight(lang, code, true).value;
} else {
return hljs.highlightAuto(code).value;
}
}
});
}])
.controller("MainController", ["$rootScope", "$scope", "marked", function MarkdownController($rootScope, $scope, marked, $http) {
$http.get('http://beta.json-generator.com/api/json/get/VyD_JWT1Q')
.then(function (res) {
$scope.todos = res.data.todo;
$scope.events = res.data.event;
$scope.aboutlongs = res.data.aboutlong;
$scope.mainpoints = res.data.mainpoint;
$scope.tags = res.data.tag;
$scope.galleries = res.data.gallery;
$scope.menus = res.data;
$scope.socials = res.data.social;
});
}]);
Thanks in advance.
Please inject $http as a dependency in your controller.
.controller("MainController", ["$rootScope", "$scope", "$http", "marked", ....
Correct your order of dependency injection in controller ( between Marked and $http). It should be like:
.controller("MainController", ["$rootScope", "$scope", "$http", "marked", function MarkdownController($rootScope, $scope,$http, marked ) {
Plunker

Factory Service is always undefined

I've spent a few hours trying to debug this with no real breakthroughs. My console.logs correctly output the load order.
- app
- factory
- controller
I'm annotating my dependencies (even though I'm not minifying at the moment).
Is there anything obviously wrong here that I am missing?
error
app
(function () {
'use strict';
console.log("running app");
var app = angular.module('InventoryProductApp', []).config(function ($logProvider) {
$logProvider.debugEnabled(true);
});
angular.element(document).ready(function () {
var app = document.getElementById('InventoryProductApp');
angular.bootstrap(angular.element(app), ['InventoryProductApp']);
});
})();
controller
(function () {
'use strict';
angular.module('InventoryProductApp').controller("LocationsController", ['$scope', '$log', 'LocationsFactory'
, function ($scope, $http, $log, LocationsFactory) {
console.log("running controller");
$scope.locations = null;
$scope.loading = false;
//private methods -------------------------------------------------------------------------------------------------------------------------------------------------------------
var fetchLocationData = function (inventoryId) {
$scope.loading = true;
console.log(LocationsFactory);
var promise = LocationsFactory.getLocationData(inventoryId);
promise.then(function (data) {
$scope.loading = false;
if (data.success) {
$scope.locations = data.locations;
}
else
{
$log.error('There was an error getting location data');
}
}, function (data) {
$scope.loading = false;
$log.error('There was an error getting location data');
});
}
//end private methods ---------------------------------------------------------------------------------------------------------------------------------------------------------
//public methods --------------------------------------------------------------------------------------------------------------------------------------------------------------
var init = function (inventoryId) {
console.log('inventoryId', inventoryId);
fetchLocationData(inventoryId);
}
//end public methods ----------------------------------------------------------------------------------------------------------------------------------------------------------
init(inventoryId); // inventoryId is found in the partialView _inventoryLocationDistribution
}]);
})();
factory
(function () {
'use strict';
angular.module('InventoryProductApp').factory('LocationsFactory', ['$http', '$q', '$log', function ($http, $q, $log) {
console.log("running factory");
return {
getLocationData: function (inventoryId) {
var def = $q.defer();
$http.get('/butthead', {
params: {
inventoryId: inventoryId
}
}).then(function (response) {
def.resolve({
success: true,
locations: data.locations
});
}, function (response) {
$log.error('failed to fetch data', response);
def.resolve({
success: false,
redirect: response.redirect
});
});
return def.promise;
}
}
}]);
})();
script load order
<script src="~/theme/modern/assets/global/plugins/angularjs/angular.min.js"></script>
<script src="~/App/Inventory/Product/ProductApp.js"></script>
<script src="~/App/Inventory/Product/LocationsFactory.js"></script>
<script src="~/App/Inventory/Product/LocationsController.js"></script>
In your controller:
angular.module('InventoryProductApp').controller("LocationsController",
['$scope', '$log', 'LocationsFactory', function ($scope, $http, $log, LocationsFactory) {
You're missing '$http' in your dependency injections, which means the LocationsFactory argument isn't filled at all.

Angular Js is not working properly

angular js not displaying anything even like simple expressions. i am tying to execute below code but no hope. can anyone help me out.
below code is for view to display.
`<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="/../../Scripts/angularsample.js"></script>
</head>
<body ng-app="spiceApp">
<div>
<div ng-controller="SpicyController">
<p> lets try some code by using service </p>
<input ng-init="message='Girish'" ng-model="message" />
<button ng-click="notify(message);">Notify{{1+2}}</button>
<p>alert will display only by clicking three times.</p>
</div>
<div ng-controller="List">
<button ng-click="bringList()">getList</button>
<table>
<tr ng-repeat="app in appslist">
<td>
{{app.Name}}
</td>
</tr>
</table>
</div>
</div>
</body>
</html>`
js code
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList().then(function (list) {
$scope.appslist = list;
});
};
}]);
myApp.factory('getList', ['$http',function ($http) {
//this code for getting list from controller.
return getList.getAppsList=function(){
$http({
method: 'GET',
url: 'Home/GetAppsList'
})
.success(function (response) {
return response.data;
}, function (error) {
console.log(error);
});
}
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);`
please tell me where i am wrong. nothing is working. expression is displaying like {{1+2}} in the ouptut.
You have a typo here:
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function
with the 2 comas so the dependancies are messed up.
i tried in different way with same view but i modified the js file now it's working fine.
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService',function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList.then(function (data) {
$scope.appslist = data;
});
};
}]);
var getList = angular.module("spiceApp").factory("getList", ['$http', function ($http, getList) {
return {
getAppsList: (function (response) {
return $http({
method: 'GET',
url: 'GetAppsList'
})
.then(function (response) {
console.log("coming from servicejs", response.data);
//return data when promise resolved
//that would help you to continue promise chain.
return response.data;
});
})()
};
return getList;
}]);

put a function of the controller inside another controller with angular

I need to put this function
function GraphsCtrl($scope, $http, $q){
$scope.chartExistencias = {
dataSource: {
load: function () {
var def = $.Deferred();
$http({ method: 'GET', url: ng.api + '/llantas/graficos/'+1 }).success(function (data) {
for(var i = 0; i<data.data.length; i++){
totalEx = data.data[i].count + totalEx;
}
$scope.totalEx = totalEx;
def.resolve(data.data);
});
return def.promise();
}
}
}
inside this controller
define([], function() {
return ['$scope', '$rootScope', '$http', '$utilities', '$appCache', '$q', function($scope, $rootScope, $http, $utilities, $appcache, $q) {
}
which works for a specific view, the point is that this is my html
<div ng-controller ='GraphsCtrl' >
<div dx-chart='chartExistencias' id='chartExistencias' s tyle="max-width:510px; min-width:400px; height:300px; float:left;"></div>
</div>
and I'm using the ng controller, what can I do?

How can a service return data and multiple promises to a controller?

I have defined a service with functions like this:
angular.module('common').factory('_o', ['$angularCacheFactory', '$http', '$q', '$resource', '$timeout', '_u',
function ($angularCacheFactory, $http, $q, $resource, $timeout, _u) {
var _getContentTypes = function ($scope) {
var defer = $q.defer();
$http.get('/api/ContentType/GetSelect', { cache: _u.oyc })
.success(function (data) {
$scope.option.contentTypes = data;
$scope.option.contentTypesPlus = [{ id: 0, name: '*' }].concat(data);
$scope.option.sContentType = parseInt(_u.oyc.get('sContentType')) || 0;
defer.resolve();
})
return defer.promise;
};
return {
getContentTypes: _getContentTypes
}
}]);
I am calling this in my controller like this:
.controller('AdminProblemController', ['$http', '$q', '$resource', '$rootScope', '$scope', '_g', '_o', '_u',
function ($http, $q, $resource, $rootScope, $scope, _g, _o, _u) {
$scope.entityType = "Problem";
_u.oyc.put('adminPage', $scope.entityType.toLowerCase());
$q.all([
_o.getContentTypes($scope),
_o.getABC($scope),
_o.getDEF($scope)
])
Am I correct in saying this is not the best way to use a service. I think I should be returning the
content type data and then in the controller assigning to the scope not in the service.
But I am not sure how to do this as my service just returns a defer.promise and I am using $q.all so I think I should populate the scope after $q.all has returned success for every call.
Can someone give me some advice on how I should return data from a service with a promise and have it populate the $scope after $q.all has completed with all calls successful ?
You are absolutely correct in saying that the controller should really be doing this, it would be much cleaner to remove the passing around of your scope (and make it more re-usable). I don't know your exact use case and it is a little confusing to read, but you can do this by hooking into the promises that are created by $http, as well as still handling when all of the promises have been completed.
fiddle: http://jsfiddle.net/PtM8N/3/
HTML
<div ng-app="myApp" ng-controller="Ctrl">
{{model | json}}
<div ng-show="loading">Loading...</div>
</div>
Angular
var app = angular.module("myApp", []);
app.service("_service", ["$http", function (http) {
this.firstRequest = function () {
return http.get("http://json.ph/json?delay=1000")
.then(function (res) {
// manipulate data
res.data.something = new Date();
return res.data;
});
};
this.secondRequest = function () {
return http.get("http://json.ph/json?delay=2000")
.then(function (res) {
// manipulate data
res.data.something = 12345;
return res.data;
});
};
this.thirdRequest = function () {
return http.get("http://json.ph/json?delay=3000")
.then(function (res) {
// manipulate data
res.data.something = "bacon";
return res.data;
});
};
}]);
app.controller("Ctrl", ["$scope", "_service", "$q", function (scope, service, q) {
scope.loading = true;
scope.model = {};
var firstRequest = service.firstRequest();
var secondRequest = service.secondRequest();
var thirdRequest = service.thirdRequest();
q.all([firstRequest, secondRequest, thirdRequest]).then(function (responses) {
scope.model.first = responses[0];
scope.model.second = responses[1];
scope.model.third = responses[2];
scope.loading = false;
});
}]);

Resources