display or hide loading from multiple controllers - angularjs

I'm trying to create a generic loading that would be shared among controllers. So, I've created a service that will control the hide/show state:
(function () {
'use strict';
var module = angular.module('main');
var serviceId = "LoadingService";
var ShowLoading = false;
function LoadingService($rootScope) {
function showLoading(value) {
$rootScope.$broadcast(LOADING_CHANGED, value);
}
var service = {
ShowLoading: showLoading
}
return service;
}
LoadingService.$inject = ['$rootScope'];
module.service(serviceId, LoadingService);
}());
here's the loading controller:
(function () {
'use strict';
var app = angular.module("main");
var controllerId = "rbLoading.controller";
function loadingController($scope, LoadingService) {
$scope.isLoading = false;
$scope.$on(LOADING_CHANGED, function (event, data) {
$scope.isLoading = data;
});
}
app.controller(controllerId, loadingController);
loadingController.$inject = ['$scope', 'LoadingService'];
}());
the html:
<div class="loading-panel" ng-if="isLoading">
<!-- loading content-->
</div>
and the directive:
(function () {
'use strict';
var loadingDirective = function (OPTIMISATION) {
return {
restrict: 'E',
templateUrl: function (element, attr) {
return 'App/components/shared/loading/loading.html';
},
controller: 'rbLoading.controller',
controllerAs: 'loading'
};
}
var app = angular.module('main');
loadingDirective.$inject = ["OPTIMISATION"];
app.directive('rbLoading', loadingDirective);
}());
When I'm changing the LoadingService value, it's triggering the LOADING_CHANGED event. The problem is that ng-if is not working as expected, although the data variable is with the right value. What am I missing?
UPDATE
Changing to ng-show almost solve the problem. For a particular scenario is not working. I'm displaying the loading while trying to get the user position using html5 GeoLocation api, and setting a timeout after 10 seconds using.
setTimeout(function () {
console.log("timeout");
LoadingService.ShowLoading(false);
}, 10000);
this setTimeout function is being triggered, however the loading keeps being displayed.

Related

How can I use a function from a directive inside a controller function?

I'm a newbie in AngularJS and I'm trying to use the goToUserLocation() function from the userLocation directive in the getMyPosition() function in the MapController. The reason I want to do this is that once the user clicks a button I want to take his location, zoom in to 40 and place it at the center of the map.
Can someone please help me with this?
Thank you.
Here are the directive, the controller and a service that the directive uses:
(function ()
{
'use strict';
angular
.module('app.map')
.directive('userLocation', userLocation);
function userLocation(geolocation)
{
return {
restrict: "A",
link: function(scope, element, attrs){
var ctrl = scope['vm'];
var goToUserLocation = UserLocationFactory();
goToUserLocation(ctrl, geolocation, ctrl.defaultLocation );
}
};
}
//Factory to build goToUserLocation function with callbacks configuration
function UserLocationFactory(cantGetLocation, notSupportedBrowser)
{
return goToUserLocation;
//function to make the map go to user location
function goToUserLocation(vm, geolocation, defaultLocation)
{
resolveErrorCallbacks();
geolocation.goToUserLocation(success, cantGetLocation, notSupportedBrowser);
function success(position)
{
var location = {
lat: position.lat,
lng: position.lng,
zoom: 15
};
configureLatlng(location);
}
function configureLatlng(location)
{
vm.map = {
center: location
};
}
function resolveErrorCallbacks(){
if( !cantGetLocation || !( typeof cantGetLocation === "function" ) )
{
cantGetLocation = function()
{
configureLatlng(defaultLocation);
};
}
if( !notSupportedBrowser || !( typeof notSupportedBrowser === "function" ) )
{
notSupportedBrowser = function()
{
configureLatlng(defaultLocation);
};
}
}
}
}
})();
Here is the controller:
(function ()
{
'use strict';
angular
.module('app.map')
.controller('MapController', MapController);
/** #ngInject */
function MapController($mdDialog, $mdSidenav, $animate, $timeout, $scope, $document, MapData,
leafletData, leafletMapEvents, api, prototypes, $window, appEnvService, geolocation) {
var vm = this;
vm.getMyPosition = getMyPosition;
function getMyPosition(){
console.log("Here is your location.");
}
Here is a service that the directive us:
(function() {
'use strict';
angular
.module('app.map')
.service('geolocation', geolocation);
function geolocation() {
/*
success - called when user location is successfully found
cantGetLocation - called when the geolocation browser api find an error in retrieving user location
notSupportedBrowser - callend when browser dont have support
*/
this.goToUserLocation = function(success, cantGetLocation, notSupportedBrowser)
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(currentPosition, function() {
cantGetLocation();
});
}
else
{
// Browser doesn't support Geolocation
notSupportedBrowser();
}
function currentPosition(position)
{
var pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
};
success(pos);
}
};
}
})();
To call a directive function from a controller you can bind a object from the controller onto the directive using the scope '='.
<body ng-controller="MainCtrl">
<div my-directive control="directiveControl"></div>
<button ng-click="directiveControl.foo()">Call Directive Func</button>
<p>{{directiveControl.fooCount}}</p>
</body>
then
app.controller('MainCtrl', function($scope) {
$scope.directiveControl = {};
});
app.directive('myDirective', function factory() {
return {
restrict: 'A',
scope: {
control: '='
},
link: function(scope, element, attrs) {
scope.directiveControl = scope.control ? scope.control : {};
scope.directiveControl.fooCount=0;
scope.directiveControl.foo = function() {
scope.directiveControl.fooCount++;
}
}
};
});
See this example:
https://plnkr.co/edit/21Fj8dvfN0WZ3s9OUApp?p=preview
and this question:
How to call a method defined in an AngularJS directive?

AngularJS Factory object not being updated on controller and view

I'm with a problem with binding an object of a Factory and a Controller and it's view.
I am trying to get the fileUri of a picture selected by the user. So far so good. The problem is that I am saving the value that file to overlays.dataUrl. But I am referencing it on the view and it isn't updated. (I checked and the value is actually saved to the overlays.dataUrl variable.
Here goes the source code of settings.service.js:
(function () {
"use strict";
angular
.module("cameraApp.core")
.factory("settingsService", settingsService);
settingsService.$inject = ["$rootScope", "$cordovaFileTransfer", "$cordovaCamera"];
function settingsService($rootScope, $cordovaFileTransfer, $cordovaCamera) {
var overlays = {
dataUrl: "",
options: {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
}
};
var errorMessages = [];
var service = {
overlays: overlays,
selectOverlayFile: selectOverlayFile,
errorMessages: errorMessages
};
return service;
function selectOverlayFile() {
$cordovaCamera.getPicture(overlays.options).then(successOverlay, errorOverlay);
}
//Callback functions
function successOverlay(imageUrl) {
//If user has successfully selected a file
var extension = "jpg";
var filename = getCurrentDateFileName();
$cordovaFileTransfer.download(imageUrl, cordova.file.dataDirectory + filename + '.' + extension, {}, true)
.then(function (fileEntry) {
overlays.dataUrl = fileEntry.nativeURL;
}, function (e) {
errorMessages.push(e);
});
}
function errorOverlay(message) {
//If user couldn't select a file
errorMessages.push(message);
//$rootScope.$apply();
}
}
})();
Now the controller:
(function () {
angular
.module("cameraApp.settings")
.controller("SettingsController", SettingsController);
SettingsController.$inject = ["settingsService"];
function SettingsController(settingsService) {
var vm = this;
vm.settings = settingsService;
activate();
//////////////////
function activate(){
// Nothing here yet
}
}
})();
Finnally on the view:
<h1>{{vm.settings.overlays.dataUrl}}</h1>
<button id="overlay" class="button"
ng-click="vm.settings.selectOverlayFile()">
Browse...
</button>
Whenever I change the value in the factory, it doesn't change in the view.
Thanks in advance!
Unfortunately Factories in angularjs are not meant to be used as two way bindings. Factories and Services are only singletons. They are only there to be used when called.
Ex Factory:
app.factory('itemFactory', ['$http', '$rootScope', function($http, $rootScope) {
var service = {};
service.item = null;
service.getItem = function(id) {
$http.get(baseUrl + "getitem/" + id)
.then(function successCallback(resp) {
service.item = resp.data.Data;
$rootScope.$broadcast("itemready");
}, function errorCallback(resp) {
console.log(resp)
});
};
return service;
}]);
I use the $broadcast so if I call getItem my controller knows to go get the fresh data.
Ex Directive:
angular.module("itemApp").directive("item", ['itemFactory', '$routeParams', '$location', '$rootScope', '$timeout', function (itemFactory, $routeParams, $location, $rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: "components/item.html",
link: function (scope, elem, attr) {
scope.item = itemFactory.item;
scope.changeMade = function(){
itemFactory.getItem(1);
}
scope.$on("itemready", function () {
scope.item = itemFactory.item;
})
}
}
}]);
So as you can see in my code above anytime I need a fresh item I use $broadcast and $on to update my service and directive. I hope this makes sense, feel free to ask any questions.
As pointed by Ohjay44, the factory is not updated on the view. The way to do it is using a directive (also as Ohjay44 said). To use $broadcast, $emit and $on and keep the encapsulation I did what is recommended by John Papa's Angular Style Guide: created a factory (in my case a named it comms).
Here goes the newly created directive (overlay.directive.js):
(function () {
angular
.module('cameraApp.settings')
.directive('ptrptSettingsOverlaysInfo', settingsOverlaysInfo);
settingsOverlaysInfo.$inject = ["settingsService", "comms"];
function settingsOverlaysInfo(settingsService, comms) {
var directive = {
restrict: "EA",
templateUrl: "js/app/settings/overlays.directive.html",
link: linkFunc,
controller: "SettingsController",
controllerAs: "vm",
bindToController: true // because the scope is isolated
};
return directive;
function linkFunc(scope, element, attrs, vm) {
vm.overlays = settingsService.overlays;
comms.on("overlaysUpdate", function (event, overlays) {
vm.overlays = overlays;
});
}
}
})();
I created overlay.directive.html with:
<div class="item item-thumbnail-left">
<img ng-src="{{vm.overlays.dataUrl}}">
<h2>{{vm.overlays.dataUrl}}</h2>
</div>
And finally I put an $emit on the settingsService where the overlay is updated:
(function () {
"use strict";
angular
.module("cameraApp.core")
.factory("settingsService", settingsService);
settingsService.$inject = ["comms", "$cordovaFileTransfer", "$cordovaCamera"];
function settingsService(comms, $cordovaFileTransfer, $cordovaCamera) {
var overlays = {
dataUrl: "",
options: {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
}
};
var errorMessages = [];
var service = {
overlays: overlays,
selectOverlayFile: selectOverlayFile,
errorMessages: errorMessages
};
return service;
function selectOverlayFile() {
$cordovaCamera.getPicture(overlays.options).then(successOverlay, errorOverlay);
}
//Callback functions
function successOverlay(imageUrl) {
//If user has successfully selected a file
var extension = "jpg";
var filename = getCurrentDateFileName();
$cordovaFileTransfer.download(imageUrl, cordova.file.dataDirectory + filename + '.' + extension, {}, true)
.then(function (fileEntry) {
overlays.dataUrl = fileEntry.nativeURL;
// New code!!!!
comms.emit("overlaysUpdated", overlays);
}, function (e) {
errorMessages.push(e);
});
}
function errorOverlay(message) {
//If user couldn't select a file
errorMessages.push(message);
//$rootScope.$apply();
}
}
})();
I used an $emit instead of a broadcast to prevent the bubbling as explained here: What's the correct way to communicate between controllers in AngularJS?
Hope this helps someone else too.
Cheers!

Updating the $scope value

I wanted to display the added users dynamically in the dashboard.
My code is in the following way.
Controller: where the actual action triggers .
Adding the user function
$scope.addUser= function(){
modalService.addUser();
}
function init(){
// Someother functions
getUserRequests()
};
function getUserRequests() {
datacontext.getExtranetUserRequests()
.then(function (data){
vm.ExtranetUserRequest = data;
});
};
Service: modalService
addUser: function (column) {
var modalInstance = $modal.open({
templateUrl: 'app/NewExtranetSite/Popup/userModal.html',
controller: 'userModal',
});
updateUser: function(){
// updates the user
});
Controller :userModal
In the userModal.html after adding the info and on clicking save, add user function will be triggered.
function addUser(){
datacontext.saveNewExtranetuserRequest($scope.user);
};
I would like to initiate the getUserRequests() after the completion of add user in the user modal
So that the newly added user can be visble on the dashboard without refreshing the page
Let me answer u shortly.
You have a view where you are adding user details from input using one form ().
On ng-submit or ng-click action you can call one method in your that particular view's controller.
Now to display user details, you might know json. So create a blank $scope variable which will contain added user details.($scope.variable=[];)
Now on submit just hit **
$sope.variable.push({'key':value,'value':value});
**
once your object is populated with new data it will automatically displayed in the view.
5. We have just awesome ng-repeat angular's directive to show dynamical list containing objects.
6. **
ng-repeat="key in variable track by $index"
**
The $modal.open function returns a promise, so it's easy to wait for the modal to close and then execute another function. Let 'addUser' return this promise, then wait for it to finish before executing getUserRequests:
in modalService:
addUser: function (column) {
var modalInstance = $modal.open({
templateUrl: 'app/NewExtranetSite/Popup/userModal.html',
controller: 'userModal',
});
return modalInstance;
}
in controller:
$scope.addUser= function(){
modalService.addUser().then((resultReturnedFromModal) => {
getUserRequests();
});
}
Sorry for the bad post.
Let me explain briefly in this post
I would like to display the added data dynamically on the page.
I have a controller where the user addition action takes place.
(function () {
'use strict';
var controllerId = 'newUser';
angular.module('app').controller(controllerId,
['modalService', '$scope', 'dataContext', newUser]);
function newUser(modalService, $scope, dataContext) {
init();
function init() {
var extranetSiteRequestId = +$routeParams.id;
if (extranetSiteRequestId && extranetSiteRequestId > 0) {
getItem(extranetSiteRequestId);
getUserRequests();
}
}
$scope.newuserRequest = function () {
modalService.addUser();
}
function getUserRequests() {
datacontext.getExtranetUserRequests().then(function (data) {
vm.UserData = data;
});
};
}
}());
I am using a service modalService to handle the add user request.
(function (){
'use strict';
var serviceId = 'modalService'
angular.module('app').service(serviceId, ['$modal', modalService]);
function modalService($modal) {
return {
addUser: function () {
var modalInstance = $modal.open({
templateUrl: 'app/NewExtranetSite/Popup/userModal.html',
controller: 'userModal',
});
modalInstance.result.then(function (userDetails) {
if (userDetails) {
alert(userDetails) ;
};
})
},
};
}
})();
finally in the userModal controller am handling the new user added request
(function () {
'use strict';
var controllerId = 'userModal';
angular.module('app').controller(controllerId, ['$scope', '$modalInstance', 'datacontext', 'common', addUserModalFunction]);
function addUserModalFunction($scope, $modalInstance, datacontext, common) {
var vm = $scope;
vm.cancel = cancel;
vm.submit = addUser;
init();
function init() {
common.logger.log("controller loaded", null, controllerId);
common.activateController([], controllerId);
}
function cancel() {
$modalInstance.close();
}
$scope.open = function ($event, opened) {
$event.preventDefault();
$event.stopPropagation();
$scope[opened] = true;
};
function addUser() {
datacontext.saveNewExtranetuserRequest($scope.user).then(function(data){
$modalInstance.close($scope.user);
});
};
};
})();
Now the problem is I would like to add a success or then function in the newUser Controller after the modalService.adduser complete
EX: modalService.addUser().then(function(results){
});
Fikkatra Thanks for the reply but couldn't able to achieve
am very bad # angular

Best way to ng-hide my headMenu from different controller

I want to hide my headmenu.
app.controller("kpiOverviewCtrl", function ($scope, $stateParams,) {
"use strict";
var setUpController = function () {
$scope.headmenu = $state.current.controller === "kpiCompareCtrl";
};
$rootScope.$on('$locationChangeSuccess', function () {
setUpController();
});
$rootScope.$on('$stateChangeSuccess', function () {
setUpController();
});
setUpController();
});
As you can see on the code it sets headmenu to true on a controller switch. It works fine. But now I want to set headmenu to true on a ng-click statment from a controller thats already been loaded.
app.controller("kpiDetailsCtrl", function ($scope, $state) {
"use strict";
$scope.loadDataForMonthView = function () {
$scope.errorNoDataForDate = false;
$scope.yearMode = false;
$scope.monthMode = true;
//Here I want to set $scope.headmenu = true;
//Other code.....
};
Any nice suggestions?
Use a broadcast. They're a great way for communication between controllers.
Create a regular function in your main controller, which you can call from within the controller itself.
app.controller('Main', function($scope) {
function setHeadMenu() {
// Set menu to true
}
$scope.$on('setHeadMenu', function() {
setHeadmenu(); // Fires on broadcast
})
});
Create an ng-click which fires a broadcast from the other controller
app.controller('Second', function($scope) {
$scope.click = function() {
$scope.$broadcast('setHeadMenu'); // Send a broadcast to the first controller
}
});
You can declare new method to $rootScope inside kpiOverviewCtrl:
app.controller("kpiOverviewCtrl", function ($scope, $stateParams, $rootScope) {
"use strict";
//your code...........
$rootScope.setUpController = setUpController;
});
And then call it from kpiDetailsCtrl controller:
app.controller("kpiDetailsCtrl", function ($scope, $state, $rootScope) {
"use strict";
$scope.loadDataForMonthView = function () {
$scope.errorNoDataForDate = false;
$scope.yearMode = false;
$scope.monthMode = true;
$rootScope.setUpController();
}
});
First dummy suggestion:
$scope.loadDataForMonthView = function () {
$scope.headmenu = true; //(or false)
}
But most likely you are using some asynchrounous call, so something like this would be better:
$scope.loadDataForMonthView = function () {
// First: you need some promise object
// the most simple is to use $http
var promise = $http({url: 'some.url', method: 'GET'});
promise.then(function() {
// the data have arrived to client
// you can hide or show menu according to your needs
$scope.headmenu = true; //(or false)
})
}
More on how $http works is in the docs https://docs.angularjs.org/api/ng/service/$http

Angular js - Using Service

Menu-Controller:
// Left Menu Start
'use strict';
angular.module("MainApp")
.controller('LeftMenuCtrl', function ($scope, $rootScope, actionCall) {
$scope.notify = {};
$scope.actionUrlCall = function(action)
{
actionCall.actionUrlCall(action, function(response){
$scope.notify = actionCall.notify;
console.log($scope.notify);
});
};
});
Now there are several html pages in view:
Each one of them has these notification directives:
<div class="col-sm-12">
<notification type="success"></notification>
<notification type="error"></notification>
<notification type="warning"></notification>
</div>
Which displays the notification as per the output from actionCall service.
I have console logged console.log($scope.notify); and I'm getting the required result. Problem is I don't know how to communicate this with the directives present on various different pages with different controllers and different scope.
Ok, so this is how I finally solved the issue.
I created a new service(menu-service.js) :
'use strict';
angular.module("MainApp")
.factory('menuClick', function($rootScope) {
var sharedService = {};
sharedService.notify = {};
sharedService.prepForBroadcast = function(msg) {
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
Then I injected my service which is named as menuClick in my menu controller and added some lines in it:
angular.module("MainApp")
.controller('LeftMenuCtrl', function ($scope, $rootScope, menuClick) {
$scope.handleMenuClick = function(action) {
menuClick.notify.warningNotify = true;
menuClick.notify.errorNotify = true;
menuClick.notify.successNotify = true;
if(!action.IsEnabled)
{
menuClick.notify.warningNotify = false;
menuClick.notify.warningMessage = "This operation is disabled ( "+action.Text+" )";
menuClick.prepForBroadcast(menuClick.notify);
}
};
});
Then I injected menuClick to the controllers where I needed to listen the Broadcast data and added following lines in those controllers:
$scope.$on('handleBroadcast', function() {
$scope.notify = menuClick.notify;
});
And it started working!!

Resources