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?
Related
How to call callback when Device returns data and pass this to the callback method.
Controller
(function() {
'use strict';
angular
.module('frontendApp')
.controller('DeviceController', DeviceController);
DeviceController.$inject = ['$scope', '$state', 'Device'];
function DeviceController ($scope, $state, Device) {
var vm = this;
vm.devices = [];
loadAll();
function updateMap(flag){
var self = this;//how to pass "this" from loadAll()?
// logic to update map
}
function loadAll() {
Device.query(function(result) {
vm.devices = result;
// Callback function here - updateMap(true)
});
}
}
})();
Service
function Device ($resource, DateUtils) {
var resourceUrl = 'api/devices/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'update': { method:'PUT' }
});
}
As discussed, you can use vm directly inside the updateMap function as below.
(function() {
'use strict';
angular
.module('frontendApp')
.controller('DeviceController', DeviceController);
DeviceController.$inject = ['$scope', '$state', 'Device'];
function DeviceController ($scope, $state, Device) {
var vm = this;
vm.devices = [];
loadAll();
function updateMap(flag){
console.log(vm.devices);
}
function loadAll() {
Device.query(function(result) {
vm.devices = result;
// Callback function here - updateMap(true)
});
}
}
})();
I have data in one controller and now I want to share it with another but both controller has different modules. I have used $rootscope but it didn't work. I have used service it also didn't work. link here Service
Is there any other way to do. I have spent one week for this please help me.
toolbar.controler
(function ()
{
'use strict';
angular
.module('app.toolbar')
.controller('ToolbarController', ToolbarController);
function ToolbarController($rootScope, $mdSidenav, msNavFoldService, $translate, $mdToast, $location, $localStorage, $http, $scope)
{
var vm = this;
vm.name = $localStorage.name;
vm.userId = $localStorage._id;
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
}
})();
The data stored here in vm.reslt.
toolbar.module.js
(function ()
{
'use strict';
angular
.module('app.toolbar', [])
.config(config);
/** #ngInject */
function config($stateProvider, $translatePartialLoaderProvider)
{
$translatePartialLoaderProvider.addPart('app/toolbar');
}
})();
Now I want that result for this controller.
sharedwishlistdetails.controller.js
(function ()
{
'use strict';
angular
.module('app.sharedwishlistdetails')
.controller('SharedWishlistDetailsController', SharedWishlistDetailsController);
/** #ngInject */
//NotificationsController.$inject = ['$http', '$location'];
function SharedWishlistDetailsController($http, $location, $localStorage, $rootScope, $scope)
{
var vm = this;
vm.uid = $localStorage._id;
}
})();
shareddata.service.js
(function ()
{
'use strict';
angular
.module('app.core')
.factory('shareData', shareDataService);
/** #ngInject */
function shareDataService($resource,$http) {
var shareData = {};
return shareData;
}
})();
write a service in 'app.toolbar' module
angular.module('app.toolbar').service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
In your toolbarController , inject ServiceA and set data -
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
ServiceA.setValue(vm.rslt);
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
Now write another service for 'app.sharedwishlistdetails' module -
angular.module('app.sharedwishlistdetails',['app.toolbar']).service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
Now inject ServiceB in your SharedWishlistDetailsController controller and access data -
var sharedData = ServiceB.getValue();
How could $rootScope failed in your code it would be appreciated if you paste your code: never mind here is an example that will help you out:
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.
The rootScope is available in the entire application.If a variable has the same name in both the current scope and in the rootScope, the application use the one in the current scope.
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
I try to call an method of civilitiyController in CustomerController. So, with my search I have found the event's manager to call method but I don't success to return the result from CivilityController to CustomerController.
I already tried this:
1/
civilitiesController :
$scope.$on("getListCivilities", function(event, args){
$scope.civilities = getCivilitiesList();
});
customersController :
$scope.$broadcast("getListCivilities");
console.dir($scope.civilities) // after run civilities = undefined
2/CivilitiesController:
$scope.$on("getListCivilities" , function(event, args){
var list = getCivilitiesList();
return list;
});
CustomersController :
$scope.civilities = $scope.$broadcast("getListCivilities");
console.dir($scope.civilities); //display var of broadcast
3/ Edit:
After first answer, I tried this :
civilities controller :
function getCivilitiesList()
{
var reqGetCivilities = $http({ url: 'api/Civilities/Get' });
reqGetCivilities.success(function(data){
$scope.civilities = data;
$scope.$broadcast("getListCivilities", { list: $scope.civilities });
return data;
});
}
getCivilitiesList();
customersController :
function test()
{
$scope.$on("getListCivilities", function (event, args) {
$scope.civilities = args.list;
console.log('test0');
console.dir($scope.civilities);
});
}
test();
$scope.$on is never executed and I don't see why.
I hope someone can help me.
check this plunker
app.controller('Controller1', function($scope) {
$scope.name = 'World';
$scope.$on('ValueUpdated', function(event, args) {
$scope.name = args.currentValue;
});
});
app.controller('Controller2', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.myData = "type here";
$scope.broadCast = function() {
$rootScope.$broadcast('ValueUpdated', {
currentValue: $scope.myData
});
}
I used broadcast, but you can do this with services and watchers too.
I guess below should work :
function CivilitiesController($scope)
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}
function CustomersController($scope)
{
$scope.$emit('someEvent', args);
}
JSFiddle (for more details) : http://jsfiddle.net/nikdtu/moo89kaw/
Ahmet Zeytindalı, this is my entire CivilitiesController :
(function () {
'use strict';
'use strict';
angular
.module('LSapp')
.controller('CivilitiesCtrl', CivilitiesCtrl)
CivilitiesCtrl.$inject = ['$scope', '$http', '$rootScope'];
function CivilitiesCtrl($scope, $http, $rootScope) {
function getCivilitiesList()
{
var reqGetCivilities = $http({ url: 'api/Civilities/Get' });
reqGetCivilities.success(function(data){
$scope.civilities = data;
});
}
getCivilitiesList();
function getList()
{
$rootScope.$broadcast("getListCivilities", { list: $scope.civilities });
}
getList();
}
})();
And the method to retreive list:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$window', '$compile','$cookies', '$state','locker','$q','$timeout', '$rootScope'];
function CustomersCtrl($scope, $http, $location, $modal, $window, $compile, $cookies, $state, locker, $q, $timeout) {
//some code
function test()
{
$scope.$on("getListCivilities", function (event, args) {
$scope.civilities = args.list;
console.log('$on args : ');
console.dir(args);
});
}
test();
}
});
The method $on doesn't run and if I put console.log($scope.civilities) after the method, the result is always undefined.
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;
}
} };
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;
});
}]);