call plugin template /page with script ui.route angularjs? - angularjs

Hey all can you help me, i want to call css and jquery file for template but one page, i have made it but it does not show its page and plugin file has been called!!
this function app.constant for call a plugin
{
app.constant('MODULE_CONFIG', [
{
name: 'alumnss',
module: true,
files: [
'public/alumni/css/icomoon.css',
'public/alumni/css/simple-line-icons.css',
'public/alumni/css/magnific-popup.css',
'public/alumni/css/owl.carousel.min.css',
'public/alumni/css/owl.theme.default.min.css',
// 'public/alumni/css/salvattore.css',
'public/alumni/css/style.css',
'public/alumni/js/modernizr-2.6.2.min.js',
'public/alumni/js/jquery.easing.1.3.js',
'public/alumni/js/jquery.waypoints.min.js',
'public/alumni/js/jquery.magnific-popup.min.js',
'public/alumni/js/owl.carousel.min.js',
'public/alumni/js/jquery.countTo.js',
'public/alumni/js/main.js'
]
}
]).config(['$ocLazyLoadProvider', 'MODULE_CONFIG', function($ocLazyLoadProvider, MODULE_CONFIG) {
$ocLazyLoadProvider.config({
debug: false,
events: false,
modules: MODULE_CONFIG
});}]);}
2. this route a page
app.config(function($stateProvider, $urlRouterProvider, MODULE_CONFIG) {
$urlRouterProvider.otherwise('/alumnis');
$stateProvider
.state('alumnis', {
url: '/alumnis',
templateUrl: 'alumni.html',
controller:'',
resolve: load(['alumnss']) // **THIS CALL FROM 'MODULE_CONFIG' has been called, But the html page not showing **
})
function load(srcs, callback) {
return {
deps: ['$ocLazyLoad', '$q',
function( $ocLazyLoad, $q ){
var deferred = $q.defer();
var promise = false;
srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
if(!promise){
promise = deferred.promise;
}
angular.forEach(srcs, function(src) {
promise = promise.then( function(){
angular.forEach(MODULE_CONFIG, function(module) {
if( module.name == src){
if(!module.module){
name = module.files;
}else{
name = module.name;
}
}else{
name = src;
}
});
return $ocLazyLoad.load(name);
} );
});
deferred.resolve();
return callback ? promise.then(function(){ return callback(); }) : promise;
}]
}
}
});
and this image, for page blank not show the template, or something wrong with the code??? help me please???

I have gotten your solution
Change the ocLazyLoad CDN like this
<script data-require="oclazyload#1.0.9" data-semver="1.0.9" src="https://cdnjs.cloudflare.com/ajax/libs/oclazyload/1.1.0/ocLazyLoad.min.js"></script>
and write the code for JQ_CONFIG not MODULE_CONFIG
var app = angular.module('routerApp');
app.constant('JQ_CONFIG', {
callplugincss: [
'style.css'
]
});
app.constant('MODULE_CONFIG', [{
name: 'ngGrid',
module: true,
files: [
'js of ng grid'
]
}]);
and change in dependency
routerApp.config(function ($stateProvider, $urlRouterProvider, MODULE_CONFIG, JQ_CONFIG) {
I think it will work. thanks.

Related

Videogular Angular video player problems with async data and `this.config` in controller

I'm using the Videogular video player for Angular. The HTML code looks like this:
<div ng-controller="ShowController as controller" class="videogular-container">
<videogular vg-theme="controller.config.theme.url">
<vg-media vg-src="controller.config.sources" vg-tracks="controller.config.tracks" vg-native-controls="true"></vg-media>
</videogular>
</div>
In the controller the code looks like this to play my video that is stored in Firebase Storage:
app.controller('ShowController', ['$sce', function($sce) {
this.config = {
preload: "auto",
sources: [
{src: $sce.trustAsResourceUrl("https://firebasestorage.googleapis.com/v0/b/myFirebaseApp.appspot.com/o/videos%2Fen%2Fkingfisher.webm?alt=media&token=b4840120-e531-4699-a757-4e0d999ce9d1"), type: "video/webm"}
],
theme: {
url: "http://www.videogular.com/styles/themes/default/latest/videogular.css"
}
};
}]);
That works great, as long I only want to play one video. But to dynamically select from an array of videos, I wrote this:
app.controller('ShowController', ['$scope', '$firebaseStorage', '$sce', function($scope, $firebaseStorage, $sce) {
var ref = firebase.database().ref();
var obj = $firebaseObject(ref.child($routeParams.id));
obj.$loaded(
function(data) {
console.log("Loaded!")
console.log(data === obj);
$scope.wordObject = data;
console.log($scope.wordObject.videos[0].videoURL);
console.log($scope.wordObject.videos[0].videoMediaFormat);
this.config = {
preload: "auto",
sources: [
{src: $sce.trustAsResourceUrl($scope.wordObject.videos[0].videoURL), type: "video/" + $scope.wordObject.videos[0].videoMediaFormat}
],
theme: {
url: "http://www.videogular.com/styles/themes/default/latest/videogular.css"
}
};
},
function(error) {
console.log("Error: ", error)
});
}]);
The videoURL and videoMediaFormat log just fine. But neither the video source nor the theme loads into the HTML view. The problem appears to be that moving this.config changed the object that this refers to. What is this.config doing?
Can I bind this to the controller using call or apply?
I figured it out:
app.controller('ShowController', ['$scope', '$firebaseObject', '$sce', function($scope, $firebaseObject, $sce) {
// Create Firebase reference
var ref = firebase.database().ref();
var obj = $firebaseObject(ref.child($routeParams.id));
$scope.wordObject = obj;
var controller = this;
obj.$loaded(
function(data) {
console.log(data === obj);
$scope.wordObject = data;
// video player
controller.config = {
preload: "auto",
sources: [
{src: $sce.trustAsResourceUrl($scope.wordObject.videos[0].videoURL), type: "video/" + $scope.wordObject.videos[0].videoMediaFormat},
],
theme: {
url: "http://www.videogular.com/styles/themes/default/latest/videogular.css"
}
};
},
function(error) {
console.log("Error: ", error)
});
}]);

How to load Angular-translate before any UI is displayed with ui-router resolve

I used angular-translate for i18n. I want to use $translatePartialLoader service to modular language key as lazy load. Also I want to use ui-router resolve option for this.
Now How to do this? Is possible add a code sample for me?
Thanks
I find solutions and solve my problem.
In config:
$translatePartialLoaderProvider.addPart('index');
$translateProvider
.useSanitizeValueStrategy(null)
.fallbackLanguage('en-us')
.registerAvailableLanguageKeys(['en-us','pt-br'], {
'en_*': 'en-us',
'pt_*': 'pt-br'
})
.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/locale_{lang}.json'
})
.useLoaderCache(true)
.useCookieStorage()
.determinePreferredLanguage();
In ui-router for index:
.state('index', {
url: '/index',
templateUrl: 'index.html',
controller:'IndexCtrl',
resolve: {
trans:['RequireTranslations',
function (RequireTranslations) {
RequireTranslations('index');
}],
dep: ['trans','$ocLazyLoad',
function(trans,$ocLazyLoad){
return $ocLazyLoad.load(['plugin']).then(
function(){
return $ocLazyLoad.load(['IndexCtrl.js']);
}
);
}]
}
})
.state('index.users',{
url: "/users",
templateUrl: "users.html",
controller:'UserListCtrl',
resolve: {
trans:['RequireTranslations',
function (RequireTranslations) {
RequireTranslations('modules/user');
}],
dep: ['trans','$ocLazyLoad',
function(trans,$ocLazyLoad){
return $ocLazyLoad.load(['UserListCtrl.js'])
}]
}
})
and in run:
app.run(function($rootScope,$translate) {
// translate refresh is necessary to load translate table
$rootScope.$on('$translatePartialLoaderStructureChanged', function () {
$translate.refresh();
});
$rootScope.$on('$translateChangeEnd', function() {
// get current language
$rootScope.currentLanguage = $translate.use();
});
})
and in RequireTranslations factory:
app.factory('RequireTranslations', function($translatePartialLoader, $translate,$rootScope) {
return function() {
angular.forEach(arguments, function(translationKey) {
$translatePartialLoader.addPart(translationKey);
});
return $translate.refresh().then(
function(){
return $translate.use($rootScope.currentLanguage);
}
);
};
});
and please note you should add $translatePartialLoader and trans as parameter in all controllers like this:
app.controller('UserListCtrl',function($scope,...,$translatePartialLoader,trans){

calling a service inside a controller in angularjs

I'm working with ng-resource to do CRUD manipulations as following :
app
.factory('candidatureService',['$resource',
function ($resource) {
return $resource('http://localhost:8080/candidature/candidats', {}, {
update: { method: "PUT"}
});
}]);
I only need PUT in my case.
and in the controller I have this :
app
.controller('CandidatureStartCtrl', function ($scope, candidatureService) {
$scope.candidature = {};
$scope.candidature.guarantor = {};
$scope.submitForm1 = function(isValid) {
console.log('validate form');
// check to make sure the form is completely valid
if (isValid) {
console.log('form 1 is amazing');
console.log($scope.user);
candidatureService.update({},{
"username": "Uchiha",
"nom": $scope.candidature.lastname,
"prenom": $scope.candidature.firstname,
"nomarab": $scope.candidature.arabicLastname,
"prenomarab": $scope.candidature.arabicFirstname,
"genre": $scope.candidature.gender,
"dateNaissance": $scope.candidature.birthdate,
"email": $scope.candidature.email,
"telephone": $scope.candidature.phoneNumber,
"photo": $scope.candidature.photo,
"cin": $scope.candidature.identityDocumentCode,
"adresse": $scope.candidature.address,
"codeMassar": $scope.candidature.codeMassar,
"lieuNaissance": $scope.candidature.placeOfBirth,
"cinPhoto": $scope.candidature.identityDocument,
"anneebac": $scope.candidature.anneebac,
"nomGarant": $scope.candidature.guarantor.fullName,
"lienGarant": $scope.candidature.guarantor.link,
"telephoneGarant": $scope.candidature.guarantor.phoneNumber,
"province": {
"codeProvince" : $scope.candidature.province
}
});
$scope.steps.step2=true;
} else {
console.log('form is invalid');
}
};
});
username is the primary key in my case.
but when I use this controller I'm getting this error message :
TypeError: candidatureService.update is not a function
at new <anonymous> (http://localhost:8080/app/scripts/controllers/candidature-start.js:106:24)
in my index.html I've declared the controller and the service as following :
<script src="scripts/controllers/candidature-start.js"></script>
<script src="scripts/service/candidatureService.js"></script>
and when I access to my page I call the 'CandidatureStartCtrl' which is declared in candidature-start.js :
.state('candidature.start', {
url: '/start',
controller : 'CandidatureStartCtrl',
templateUrl: 'views/tmpl/frontend/candidature-start.html',
containerClass: 'hz-menu',
resolve: {
plugins: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load([
'scripts/vendor/slider/bootstrap-slider.js',
'scripts/vendor/touchspin/jquery.bootstrap-touchspin.js',
'scripts/vendor/touchspin/jquery.bootstrap-touchspin.css',
'scripts/vendor/filestyle/bootstrap-filestyle.min.js'
]);
}]
}
})
So why I'm getting that error message it took me 3 hours but I couldn't figure out whats the problem !
Method names in your services get prepended with a $ when you use $resource, so the call should be to candidatureService.$update

Pass parameter from controller to services in angularjs

How can i have one service or factory receiving two parameters from many controllers?
One parameter for the url, other for the file name to be stored on the filesystem.
I will have many controllers using this service, each passing his own url and filenames that reads the url and generate a pdf.
I will always store the last downloaded pdf providing an "open last pdf" button, that will use the name parameter.
I will have a "generate new pdf" button coming from the url.
I do follow this tutorial https://blog.nraboy.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/ and everything works fine.
I am using cordova file-transfer and inappbrowser cordova plugins
These sections will receive the parameters :
dirEntry.getFile("pdf-number-1.pdf",
ft.download(encodeURI("http://www.someservice.com"),p,
My attempt always trigger the message unknow pdfService provider
Wich concepts of angular i am missing ? How can i fix it ?
In services.js i have :
.service('pdfService', function($scope, $ionicLoading){
if( window.cordova && window.cordova.InAppBrowser ){
window.open = window.cordova.InAppBrowser.open;
console.log("InAppBrowser available");
} else {
console.log("InAppBrowser not available");
}
this.download = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory("ExampleProject",{create: true},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI("http://www.someservice.com"),
p,
function(entry) {
$ionicLoading.hide();
$scope.imgFile = entry.toURL();
},
function(error) {
$ionicLoading.hide();
alert("Download Error Source -> " + error.source);
},
false,
null
);
},
function() {
$ionicLoading.hide();
console.log("Get file failed");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}
this.load = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
"ExampleProject",
{
create: false
},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: false,
exclusive: false
},
function gotFileEntry(fe) {
$ionicLoading.hide();
$scope.imgFile = fe.toURL();
alert(fe.toURL());
window.open(fe.toURL(), '_system', 'location=no,toolbar=yes,closebuttoncaption=Close PDF,enableViewportScale=yes');
},
function(error) {
$ionicLoading.hide();
console.log("Error getting file");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Error requesting filesystem");
});
}
});
And in the controller :
.controller('SomeCtrl', function($scope, $ionicPopup, pdfService) {
...
pdfService.download = function(url) {
console.log('pdfService download');
}
pdfService.load = function() {
console.log('pdfService load');
}
You will need to inject the service to your controllers and call a function with the two params you want as your arguments.
eg.
.service('pdfService', function(){
var lastUrl;
var lastFileName
return {
createPdf(url, fileName){
//do processing
lastUrl = url;
lastFileName = fileName
},
loadLastPdf(){
//use lastUrl and lastFileName
}
}
}
and in your controller:
.controller('SomeCtrl', function(pdfService) {
pdfService.createPdf('http://example.com', 'file.pdf');
// or pdfService.loadLastPdf();
}
That being said, the error you are reporting means that the DI is unable to find a service with the name pdfService to inject to your controller. This might be because you forgot to include the service.js file to your html as a script tag (if you are doing it like that) or you forgot to add it as a dependency using require (if you are using sth like browserify) or maybe if you are minifying your code since you are not using the minsafe syntax

AngularJS, ocLazyLoad & loading dynamic States

app
define(['angular', 'angular-ui-router', 'ocLazyLoad', 'config/common',
'layout/services/menuService'],
function(angular) {
'use strict';
var $stateProviderRef = null;
var $urlRouterProviderRef = null;
return angular.module('app', ['ui.router', 'oc.lazyLoad', 'app.common', 'app.layout']);
});
app.config
define(['app'],function(app){
app.config(function($locationProvider, $stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$urlRouterProviderRef = $urlRouterProvider;
$stateProviderRef = $stateProvider;
$urlRouterProviderRef.otherwise('/');
$locationProvider.html5Mode({enable: true, requireBase: false}); //.hashPrefix('!');
$ocLazyLoadProvider.config({
events: true,
debug: false
}); }); });
app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(viewStates) {
var startUp = undefined;
angular.forEach(viewStates, function(viewState, key){
var viewStateUrl = undefined;
if (viewState.isStartUp == true && startUp == undefined) {
startUp = viewState.name;
}
var state = {
"url": viewState.url,
"name": viewState.name,
"views": []
}
angular.forEach(viewState.views, (function(view) {
var myView = {
"controller" : view.controller,
"templateUrl" : view.templateUrl,
"resolve" : { }
};
myView.resolve.loadController = function($ocLazyLoad)
{
return $ocLazyLoad.load(
{
"name": view.moduleName,
"files": view.controllerFiles
})
};
state.views[view.viewName] = myView ;
}));
$stateProviderRef.state(viewState.name, state);
})
$state.go(startUp);
})
}); });
Solved:
The error was in a combination of areas. The complete solution is below. I am not happy about the solution to this outcome as mentioned below and welcome ideas. Basically I would have preferred a more agnostic binding of the resolve method to my states in the app.run file.
I have this working, although I am not quite happy with the code and I will explain at the end. First off, I found a path to my solution from this Stackoverflow Prior Question
1. app.js
The only change I made from above was to add the ShellCtrl location:
define(
[
'angular', 'angular-ui-router', 'ocLazyLoad', 'config/common',
'layout/services/menuService', 'layout/controllers/ShellCtrl'],
.....
2. app.config:
Nothing changed from above.
3. app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(states) {
angular.forEach(states, function (state) {>
try{
/// for the Header
state.views.header.resolve[state.views.header.data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views.header.data.controllerAlias,
"files": state.views.header.data.controllerFiles})};
/// for the Footer
state.views.footer.resolve[state.views.footer.data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views.footer.data.controllerAlias,
"files": state.views.footer.data.controllerFiles})};
}catch(e){
}
console.log(state);
$stateProviderRef.state(state.name, state);
})
$state.go('app.dashboard');
})
}); });
4. With this as my JSON:
[ { "name": "app", "abstract": true, "url": "", "templateUrl": "app/layout/views/tpl.shell.html", "controller": "ShellCtrl" }, {
"name": "app.dashboard",
"views": {
"header": {
"templateUrl": "app/layout/views/tpl.header.html",
"controller": "HeaderCtrl as header",
"resolve": {},
"data": {
"controllerAlias": "app.layout",
"controllerFiles": [
"app/layout/layout.module.js",
"app/layout/controllers/HeaderCtrl.js"
]
}
},
"footer": {
"templateUrl": "app/layout/views/tpl.footer.html",
"controller": "FooterCtrl as footer",
"resolve": {},
"data": {
"controllerAlias": "app.layout",
"controllerFiles": [
"app/layout/layout.module.js",
"app/layout/controllers/FooterCtrl.js"
]
}
}
} }]
5. Shell.html
<div data-ng-controller="ShellCtrl">{{shell.pageTitle}}
<div data-ui-view="header"></div>
<div data-ui-view="footer"></div>
</div>
6 Sample Controller:
angular.module('app.layout').controller('HeaderCtrl', HeaderCtrl);
/* #ngInject */
function HeaderCtrl($scope) {
var header = this;
header.pageTitle = 'Response coming from HeaderCtrl';
}
7. With this as the output:
What I do not like:
All components of my dashboard are interchangeable. Nothing is static. Depending on the "overall" view, the Header, Footer, SideMenu and Content all change. The link I mentioned above had only 1 interchangeable part, "the Feature" which I assume was main content.
I do not like the fact that I had to hard code each view in the my app.run relative to binding the resolve to each.
If someone knows how I can make this more agnostic, I would greatly appreciate input.
All components of my dashboard are interchangeable. Nothing is static. Depending on the "overall" view, the Header, Footer, SideMenu and Content all change. The link I mentioned above had only 1 interchangeable part, "the Feature" which I assume was main content.
I do not like the fact that I had to hard code each view in the my app.run relative to binding the resolve to each.
If someone knows how I can make this more agnostic, I would greatly appreciate input.
To make this more agnostic, you could implement something more along the lines of this.
Use object properties to iterate each and attempt to load into the respective resolve. Adding more error handling and checks would also help with stability.
3. app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(states) {
angular.forEach(states, function (state) {>
try{
/// try to load for each each view
for (var view in state.views)
{
if (state.views[view]['data']){
state.views[view].resolve[state.views[view].data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views[view].data.controllerAlias,
"files": state.views[view].data.controllerFiles
}
)};
}
}
}catch(e){
}
console.log(state);
$stateProviderRef.state(state.name, state);
})
$state.go('app.dashboard');
})
}); });

Resources