i try to make loading icon appears in all website while requests in all components that requires time in loading i write this code but it didn't work !
this is the directive and controller
(function() {
'use strict';
angular
.module('xreview')
.directive('loading', loading);
/** #ngInject */
function loading() {
var directive = {
restrict: 'E',
templateUrl: 'app/components/directives/loading/loading.html',
scope: {
},
controller: loadingController,
controllerAs: 'scope',
bindToController: true
};
return directive;
/** #ngInject */
function loadingController($rootScope , $httpInterceptor ) {
return function ($scope, element, attrs) {
$scope.$on("loader_show", function () {
return element.show();
});
return $scope.$on("loader_hide", function () {
return element.hide();
});
};
}
}
})();
this is the interceptor factory
(function() {
'use strict';
angular
.module('xreview')
.factory('httpInterceptor', httpInterceptor);
/** #ngInject */
function httpInterceptor($q, $rootScope, $log) {
var numLoadings = 0;
return {
request: function (config) {
numLoadings++;
// Show loader
$rootScope.$broadcast("loader_show");
return config || $q.when(config)
},
response: function (response) {
if ((--numLoadings) === 0) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return response || $q.when(response);
},
responseError: function (response) {
if (!(--numLoadings)) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return $q.reject(response);
}
};
}
})();
and i injected this in config
$httpProvider.interceptors.push('httpInterceptor');
for example this is a service of on component of the components
vm.postAllComment = function(file){
vm.commentig = true;
var modal = {
comment: vm.allCommentText
};
if (file.file_name != 'Post') {
modal.post_file = file.id;
}
userService.one('reviews', id).post('comments', modal).then(function(result){
vm.commentig = false;
vm.allComments.push.apply(vm.allComments, [{
user: result.user,
content: result.comment,
id: result.id
}]);
vm.allCommentText = '';
vm.post.comments_count ++;
}, function(error){
// error post comment
if (error.status == 403)
userService.userUnauthenticatedHandler();
vm.commentig = false;
});
};
this is the html
<div id="loaderDiv" loading>
<img src="./assets/image/spinner.gif" class="ajax-loader"/>
</div>
Related
(function() {
'use strict';
angular
.module('autocompleteCustomTemplateDemo', ['ngMaterial'])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q, $log, $scope, $http) {
var self = this;
$scope.service_details = [];
$scope.productdetail == [];
$scope.add = function() {
$scope.show_servicelist = true;
$scope.type = function(e) {
alert(e);
}
$scope.service_details.push(JSON.parse($scope.productdetails));
}
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
function querySearch(query) {
var results = query ? self.repos.filter(createFilterFor(query)) : self.repos,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function() {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
$scope.productdetails = JSON.stringify(item);
}
function loadAll() {
var repos = [{
'product_gid': '1',
'product_name': 'stabilizer',
'forks': '16,175',
}, {
'product_gid': '2',
'product_name': 'stand',
'forks': '760',
}, {
'product_gid': '3',
'product_name': 'ac',
'forks': '1,241',
},
];
return repos.map(function(repo) {
repo.value = repo.product_name.toLowerCase();
return repo;
});
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
})();
app.service("productservice", function($http) {
this.getproduct = function() {
deggure
var response = $http.get("/Productjson/");
return response;
}
});
I'm displaying angularjs file for listing autocomplete, now i have added new service file to get some data.I want to send the service data into app code, i dont know how to connect service with controller code.when i try to connect i got syntax error. please modify the code and guide me to fetch the service data .
This is full sample to show you how to use service in angularjs with controller:
var app = angular.module("app", []);
app.controller("ctrl", function($scope, service) {
$scope.alert = function() {
service.alert();
}
$scope.console = function() {
service.console();
}
})
app.service("service", function() {
this.alert = function() {
alert("hey")
}
this.console = function() {
console.log("hey")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button ng-click="alert()">alert</button>
<button ng-click="console()">console</button>
</div>
This is how you write a service-
I prefer factory:
(function() {
'use strict';
angular
.module('app')
.factory('productservice', productservice);
function productservice($q, $http) {
return {
getproduct : getproduct
};
function getproduct(){
var d = $q.defer();
$http({
method: 'GET',
url: 'url'
}).success(function(response){
d.resolve(response);
}).error(function(response){
d.reject(response);
});
return d.promise;
}
}
})();
Here;s controller
(function() {
'use strict';
angular
.module('app')
.controller('AppController', AppController);
function AppController(
$scope, productservice
) {
function getproduct(){
productservice.getproduct().then(function(response){
//got the response here
}, function(){
});
}
}
})();
With my below angular1.x script code for image annotation I have searched for a solution to solve my conversion error but I didn't get many equalents of angular1.x code in angular4. The error is a runtime error for angular1.x when I try to convert into Angular4. See below.
For $inject I use #inject but it is quite difficult to use it in my code for converting angular 1.x image annotation to angular4 image annotation.
Image annoation in angular1.x
------------------------------
annotoriousAnnotateDirective.$inject = ['annotoriousService', 'setTimeout()'];
annotoriousAnnotateDirective(annotoriousService, setTimeout(()=> {
service = {
restrict: 'A',
link: annotateLink,
priority: 100
},
return service;
link.$inject = ['$scope', '$element', '$attributes'];
annotateLink($scope, $element, $attributes)=> {
if ($attributes.src) {
annotoriousService.makeAnnotatable($element[0]);
} else {
$element.bind('load', function () {
$scope.$apply(function () {
annotoriousService.makeAnnotatable($element[0]);
});
});
}
}
}, 200);
annotoriousDirective.$inject = ['$compile', '$rootScope', '$http', '$parse', '$timeout', 'annotoriousService'];
annotoriousDirective($compile, $rootScope, $http, $parse, $timeout, annotoriousService)=> {
let service = {
restrict: 'E',
scope: {
open: '=',
options: '=',
onOpen: '&',
onLoad: '&',
onComplete: '&',
onCleanup: '&',
onClosed: '&'
},
require: 'annotorious',
link: link,
controller: controller,
controllerAs: 'vm'
};
return service;
controller.$inject = ['$scope'];
controller($scope) {
}
link.$inject = ['$scope', '$element', '$attributes'];
function link($scope, $element, $attributes, controller) {
var cb = null;
$scope.$watch('open', function (newValue, oldValue) {
//console.log("watch $scope.open(" + $scope.open + ") " + oldValue + "->" + newValue);
if (oldValue !== newValue) {
updateOpen(newValue);
}
});
$scope.$on('$destroy', function () {
$element.remove();
});
init();
updateOpen(newValue) {
if (newValue) {
init(newValue);
} else {
if (options.annotationsFor) {
let annotatables = $(options.annotationsFor);
annotatables.each(function (idx) {
let item = this;
annotoriousService.makeAnnotatable(item);
});
}
}
}
init(open) {
let options = {
//href: $attributes.src,
annotationsFor: $attributes.annotationsFor,
onOpen() {
if (this.onOpen && this.onOpen()) {
this.onOpen()();
}
},
onLoad() {
if (this.onLoad && this.onLoad()) {
this.onLoad()();
}
},
onComplete() {
onComplete();
if (this.onComplete && this.onComplete()) {
this.onComplete()();
}
},
onCleanup() {
if (this.onCleanup && this.onCleanup()) {
this.onCleanup()();
}
},
onClosed() {
$scope.$apply(function () {
$scope.open = false;
});
if ($scope.onClosed && $scope.onClosed()) {
$scope.onClosed()();
}
}
};
if (options) {
Object.assign(options, this.options);
}
for (let key in options) {
if (options.hasOwnProperty(key)) {
if (typeof(options[key]) === 'undefined') {
delete options[key];
}
}
}
if (typeof(open) !== 'undefined') {
options.open = open;
}
$timeout(function () {
if (options.annotationsFor) {
$(options.annotationsFor).each(function (i) {
var itemToAnnotate = this;
annotoriousService.makeAnnotatable(itemToAnnotate);
});
}
}, 0);
}
My error code:
I found equalent for #Inject in angular4 ,
import { Inject } from '#angular/core';
import { ourservice } from 'servicepath';
export class{
constructor(#Inject(Ourservice / Directive/ etc) private ourservice){
//our functionality
}
}
If any corrections please let me know, I am still looking solution for Image annotation in angular4
I have successfully implemented most of what is described here.
https://github.com/colthreepv/angular-login-example
My issue now is that the stateChangeStart event-handler in my login service does not seem to be registered yet when my grandfather resolve executes. The event handler never fires when I initially load the page, it only fires when I change state again after loading the first state. This makes me thing that my resolve is being executed before the stateChangeStart handler in my login-service has been registered. What can I do to make sure the event handlers has been registered when my root state resolve executes?
The global app route and the resolve:
.state('app', {
abstract: true,
templateUrl: 'vassets/partials/partial-nav.html',
resolve: {
'login': ['loginService','$q', '$http', function (loginService, $q, $http) {
loginService.pendingStateChange;
var roleDefined = $q.defer();
/**
* In case there is a pendingStateChange means the user requested a $state,
* but we don't know yet user's userRole.
*
* Calling resolvePendingState makes the loginService retrieve his userRole remotely.
*/
if (loginService.pendingStateChange) {
return loginService.resolvePendingState($http.get('/session'));
} else {
roleDefined.resolve();
}
return roleDefined.promise;
}]
}
})
My login-service looks like this (the handlers are setup by the managePermissions() call at the bottom of the service):
/*global define */
'use strict';
define(['angular'], function(angular) {
/* Services */
angular.module('myApp.services', [])
.provider('loginService', function () {
var userToken = localStorage.getItem('userToken'),
errorState = 'app.error',
logoutState = 'app.home';
this.$get = function ($rootScope, $http, $q, $state, AUTH_EVENTS) {
/**
* Low-level, private functions.
*/
var managePermissions = function () {
// Register routing function.
$rootScope.$on('$stateChangeStart', function (event, to, toParams, from, fromParams) {
if (wrappedService.userRole === null) {
wrappedService.doneLoading = false;
wrappedService.pendingStateChange = {
to: to,
toParams: toParams
};
return;
}
if (to.accessLevel === undefined || to.accessLevel.bitMask & wrappedService.userRole.bitMask) {
angular.noop(); // requested state can be transitioned to.
} else {
event.preventDefault();
$rootScope.$emit('$statePermissionError');
$state.go(errorState, { error: 'unauthorized' }, { location: false, inherit: false });
}
});
};
/**
* High level, public methods
*/
var wrappedService = {
loginHandler: function (data, status, headers, config) {
// update user
angular.extend(wrappedService.user, data.user);
wrappedService.isLogged = true;
wrappedService.userRole = data.user.roles[0].roleName;
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$rootScope.currentUser = data.user;
return data.user;
},
loginUser: function (httpPromise) {
httpPromise.success(this.loginHandler);
},
resolvePendingState: function (httpPromise) {
var checkUser = $q.defer(),
self = this,
pendingState = self.pendingStateChange;
httpPromise.success(
function success(httpObj) {
if (!httpObj.user) {
getLoginData();
}
else {
self.loginHandler(httpObj);
}
}
);
httpPromise.then(
function success(httpObj) {
self.doneLoading = true;
if (pendingState.to.accessLevel === undefined || pendingState.to.accessLevel.bitMask & self.userRole.bitMask) {
checkUser.resolve();
} else {
checkUser.reject('unauthorized');
}
},
function reject(httpObj) {
checkUser.reject(httpObj.status.toString());
}
);
self.pendingStateChange = null;
return checkUser.promise;
},
/**
* Public properties
*/
userRole: null,
user: {},
isLogged: null,
pendingStateChange: null,
doneLoading: null
};
managePermissions();
return wrappedService;
};
})
});
I am trying to create a tag layout filled with categories, but I am not getting my Authentication because I am trying to resolve that service in my Router.
this is my Router code
(function () {
'use strict';
angular
.module('learningApp')
.config(sslRouter);
// Minification safe dependency Injection
sslRouter.$inject = ['$stateProvider'];
function sslRouter ($stateProvider) {
// SSL Route Definition
$stateProvider.state('ssl', {
parent: 'policy',
url: '/ssl',
data: {
roles: ['USER']
},
views: {
'policyConfig': {
templateUrl: 'components/configuration/service/policy/ssl/ssl.tpl.html',
controller: 'SSL'
}
},
resolve: {
'sslServiceData': function(sslService) {
return sslService.promise;
}
}
});
}
}());
This is my Service
(function() {
'use strict';
angular
.module('learningApp')
.factory('sslService', sslResource);
sslResource.$inject = ['Principal', '$resource', 'BASE_URL', 'exDomainService'];
function sslResource (Principal, $resource, BASE_URL, exDomainService) {
debugger;
var res = $resource(BASE_URL + '/api/companies/' + Principal.company() + '/sconfig/ssl/sslConfiguration', {}, {
query: {
method: 'GET',
isArray: false
},
update: {
method: 'PUT'
}
});
var data = {};
var servicePromise = _initService();
servicePromise.$promise.then(function (d) {
data = d;
if (!data.excludedCategories) {
data.excludedCategories = [];
}
if (!data.excludedDomains) {
data.excludedDomains = [];
}
exDomainService.tableData = getExcludedDomains();
});
function _initService () {
return res.query();
}
return {
promise: servicePromise,
rest: res
}
}
}());
This is my controller
(function() {
'use strict';
angular
.module('learningApp')
.controller('SSL', SSLController);
SSLController.$inject = ['$scope', 'sslService', 'preDefinedCategoryService', '$timeout', 'exDialog', 'exDomainService'];
function SSLController ($scope, sslService, preDefinedCategoryService, $timeout, exDialog, exDomainService) {
var vm = $scope;
/**
* #desc Flags for different type checks
* Booleans and Categories
*/
vm.flags = {
// By default true
enableInspectSSLTraffic: sslService.getSSlInspectionFlag(),
allowUntrustedCertificates: sslService.getUntrustedCertificatesFlag(),
allowHostnameMismatch: sslService.getHostnameMismatchFlag(),
selectedCategory: undefined,
initializing: true
};
vm.excludedCategories = sslService.getExcludedCategories();
vm.predefinedCategories = preDefinedCategoryService.rest.query();
vm.predefinedCategories.$promise.then(function() {
vm.categories = _processedCategories(vm.predefinedCategories, vm.excludedCategories);
});
}
}());
So basically problem is, I am getting Principal.Identity as undefined, but if I remove resolution from Router, I got identity but then I lose my data coming from service. I want my service to be loaded completely before its Controller, and I want my principal service to be loaded before service.
for Reference, This is my Principal Class
'use strict';
angular.module('learningApp')
.service('Principal',['$q', 'Account', 'localStorageService', function Principal($q, Account, localStorageService) {
var _identity,
_authenticated = false;
return {
isIdentityResolved: function () {
return angular.isDefined(_identity);
},
isAuthenticated: function () {
return _authenticated;
},
isInRole: function (role) {
if (!_authenticated || !_identity || !_identity.roles) {
return false;
}
return _identity.roles.indexOf(role) !== -1;
},
isInAnyRole: function (roles) {
if (!_authenticated || !_identity.roles) {
return false;
}
for (var i = 0; i < roles.length; i++) {
if (this.isInRole(roles[i])) {
return true;
}
}
return false;
},
company: function () {
debugger;
if (_identity) return _identity.companyId;
},
authenticate: function (identity) {
_identity = identity;
_authenticated = identity !== null;
},
identity: function (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// rather than retrieving from server, use cookie or whatever method
var cookieFound = UTIL.cookie("token");
if (cookieFound) {
var response = JSON.parse(JSON.parse(cookieFound));
var expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
localStorageService.set('token', response);
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(function (account) {
account.data.roles = ["ADMIN", 'USER'];
account.data.langKey = "en";
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
})
.catch(function() {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
});
return deferred.promise;
}
};
}]);
Hi I am trying to create a display loading box implementation but I seem to have some problems.Here is what I have so far:
I have created an httpInterceptor:
mainModule.factory('httpLoadingInterceptorSvc', ['$q', '$injector', 'EVENTS', function ($q, $injector, EVENTS) {
var httpInterceptorSvc = {};
httpInterceptorSvc.request = function (request) {
var rootScope = $injector.get('$rootScope');
rootScope.$broadcast(EVENTS.LOADING_SHOW);
return $q.when(request);
};
httpInterceptorSvc.requestError = function (rejection) {
hideLoadingBox();
return $q.reject(rejection);
};
httpInterceptorSvc.response = function (response) {
hideLoadingBox();
return $q.when(response);
};
httpInterceptorSvc.responseError = function (rejection) {
hideLoadingBox();
return $q.reject(rejection);
};
function hideLoadingBox() {
var $http = $injector.get('$http');
if ($http.pendingRequests.length < 1) {
var rootScope = $injector.get('$rootScope');
rootScope.$broadcast(EVENTS.LOADING_HIDE);
}
}
return httpInterceptorSvc;
}]);
I have then added the directive to the interceptors of the httpProvideR:
$httpProvider.interceptors.push('httpLoadingInterceptorSvc');
I then created a directive:
mainModule.directive('loadingDir', ['EVENTS', function (EVENTS) {
var loadingDir = {
restrict: 'E',
templateUrl: 'App/scripts/main/directives/loading/LoadingDir.html'
};
loadingDir.link = function (scope, element) {
element.hide();
scope.$on(EVENTS.LOADING_SHOW, function () {
element.show();
});
scope.$on(EVENTS.LOADING_HIDE, function () {
element.hide();
});
};
return loadingDir;
}]);
And then added a simple ajaxCall that alerts a message on the controller:
dataSvc.getCurrentDate().then(function(currentDate) {
alert(currentDate);
});
I put th edirective on the html page:
<loading-dir></loading-dir>
Now my problem is that the directive code gets executed after the controller code this makes the dierective relatively useles until the page is loaded.Is there any way to make the directive code execute before the controller?
You can prepend a div to your page:
<body>
<div controller="beforeController">
<loading-dir></loading-dir>
</div>
[Rest of the page]
</body>
And beforeController should be loaded instantly.