Ok so, for the record, i had a working project, i had to change the grunt workflow of it, and now angular-ui-router throws me an ununderstandable error.
here is what i get when i follow angularjs links :
Failed to instantiate module app due to:
Failed to instantiate module ui.router due to:
Failed to instantiate module ui.router.state due to:
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=app&p1=Error%3A%20…Flocalhost%3A8080%2Fapp%2Fcomponents%2Fangular%2Fangular.min.js%3A38%3A135)(anonymous
function) # angular.min.js:6(anonymous function) # angular.min.js:35r
# angular.min.js:7g # angular.min.js:34ab # angular.min.js:38d #
angular.min.js:17uc # angular.min.js:18Jd #
angular.min.js:17(anonymous function) #
angular.min.js:250n.Callbacks.j #
jquery.min.js:2n.Callbacks.k.fireWith # jquery.min.js:2n.extend.ready
# jquery.min.js:2I # jquery.min.js:2
im quite lost, i tryed downgrading to angularjs 1.3.15, didnt bring anything. The order of inclusion of scripts is the following :
components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js
components/jquery/dist/jquery.min.js
components/highcharts/highcharts.js
components/bootstrap/dist/js/bootstrap.min.js
components/socket.io-client/socket.io.js
components/bootstrap-switch/dist/js/bootstrap-switch.min.js
components/lodash/lodash.min.js
components/gsap/src/minified/TweenMax.min.js
components/gsap/src/minified/easing/EasePack.min.js
components/PreloadJS/lib/preloadjs-0.6.1.min.js
components/humanize-duration/humanize-duration.js
components/momentjs/min/moment-with-locales.min.js
components/angular/angular.min.js
components/angular-ui-router/release/angular-ui-router.min.js
components/angular-cookies/angular-cookies.min.js
components/ng-tags-input.min/ng-tags-input.min.js
components/angular-sanitize/angular-sanitize.min.js
components/angular-animate/angular-animate.js
components/restangular/dist/restangular.min.js
components/angular-fullscreen/src/angular-fullscreen.js
components/angular-bootstrap/ui-bootstrap.min.js
components/angular-bootstrap/ui-bootstrap-tpls.min.js
components/angular-bootstrap-switch/dist/angular-bootstrap-switch.min.js
components/highcharts-ng/dist/highcharts-ng.min.js
components/ng-droplet/dist/ng-droplet.min.js
components/angular-timer/dist/angular-timer.min.js
src/constants-app.js src/app.js
src/admin/admin-controller.js
src/admin/events/events-controller.js
src/admin/moderation/bans-controller.js
src/admin/moderation/message-modal/message-modal-controller.js
src/admin/moderation/moderation-controller.js
src/admin/partners/partners-controller.js
src/admin/reports/reports-controller.js
src/admin/user/invites/invites-controller.js
src/admin/user/linked/linked-accounts-controller.js
src/admin/user/password/password-controller.js
src/admin/user/user-controller.js src/admin/votes/votes-controller.js
src/adminboard/adminboard-controller.js src/root-controller.js
src/shared/alerts/alerts-controller.js
src/shared/alerts/alerts-directive.js
src/shared/clock/clock-directive.js src/shared/crap.js
src/shared/filters/url-filter.js src/shared/main-controller.js
src/shared/modals/confirm-modal-controller.js
src/shared/purchase-credit-modal/purchase-credit-controller.js
src/shared/purchase-modal/purchase-modal-controller.js
src/shared/services/event-service.js
src/shared/services/message-service.js
src/shared/services/modal-helper-service.js
src/shared/services/queue-service.js
src/shared/services/socket-service.js
src/shared/services/user-service.js
src/shared/services/vote-service.js
src/shared/spinner/spinner-directive.js
src/shared/spinner/spinner-service.js
src/wall/bottomOverlay/bottomOverlay-controller.js
src/wall/bottomOverlay/bottomOverlay-directive.js
src/wall/counters/counters-controller.js
src/wall/counters/counters-directive.js
src/wall/messages/messages-directive.js
src/wall/messages/messages-settings-controller.js
src/wall/slideshow/slideshow-directive.js
src/wall/slideshow/slideshow-settings-controller.js
src/wall/topOverlay/topOverlay-controller.js
src/wall/topOverlay/topOverlay-directive.js
src/wall/vote/vote-directive.js src/wall/wall-controller.js
I separated the scrips in interesting blocks. Where i include angular, ui router, and other pieces.
Here is my app.js file content :
// Declare modules.
angular.module('app')
//ui.routes
.config(['$stateProvider','$urlRouterProvider','$locationProvider',function($stateProvider, $urlRouterProvider, $locationProvider) {
"use strict";
$locationProvider.html5Mode(true); //Remove # in angular urls.
$stateProvider
.state('root',{ //here we resolve all the application wide stuff. Like user.
url : '',
controller : 'rootController',
template : '<ui-view id="rootView"></ui-view>',
resolve : {
user : ['Restangular',function(Restangular){
return Restangular.all('users').customGET('self');
}]
}
})
//MODALS
//BUY CREDIT
.state('purchaseCredit',{
url : '/purchaseCredit'
})
.state('slideShowSettings',{
url : '/slideShowSettings'
})
.state('messagesSettings',{
url : '/messageSettings'
})
.state('root.admin',{
url : '/admin',
templateUrl : 'src/admin/admin.html',
controller : 'adminController'
})
//show user account infos, and actions.
.state('root.admin.user',{
url : '/user',
templateUrl : 'src/admin/user/user.html',
controller: 'userController'
})
//edit user password
.state('root.admin.user.password',{
url : '/password',
templateUrl : 'src/admin/user/password/password.html',
controller : 'passwordController'
})
//show invites list.
.state('root.admin.user.invites',{
url : '/invites',
templateUrl : 'src/admin/user/invites/invites.html',
controller : 'invitesController',
resolve : {
invites: ['Restangular', 'user', function (Restangular, user) {
return Restangular.all('invites').getList({parentId : user._id}); //todo limit to my invites.
}]
}
})
//show one invite.
/* .state('root.admin.user.invites.detail',{
url : '/:id',
templateUrl : 'src/admin/user/invites/invite.html',
controller : 'inviteController',
resolve : {
invite : ['$stateParams', function($stateParams){
if(!$stateParams.id){ return {}; }
return Restangular.one('invites',$stateParams.id).get();
}]
}
})*/
/* LINKED ACCOUNTS */
//list of linked accounts ( people who accepted invite )
.state('root.admin.user.linkedAccounts',{
url : '/linkedAccounts',
templateUrl : 'src/admin/user/linked/linkedAccounts.html',
controller : 'linkedAccountsController',
resolve : {
linkedAccounts : ['Restangular', 'user', function (Restangular, user) {
var query = { parent : user._id/*, sort : '_id', limit : 20, skip : 0*/};
console.warn('gonna fetch', query);
return Restangular.all('users').getList(query);
}]
}
})
.state('root.admin.events',{
url : '/events',
templateUrl : 'src/admin/events/events.html',
controller : 'eventsController'
})
.state('root.admin.moderation', {
url: '/moderation',
templateUrl : 'src/admin/moderation/moderation.html',
controller: 'moderationController'
})
.state('root.admin.bans',{
url : '/bans',
templateUrl : 'src/admin/moderation/bans.html',
controller : 'bansController'
})
.state('root.admin.reports',{
url : 'admin.reports',
templateUrl : 'src/admin/reports/reports.html',
controller : 'reportsController'
})
.state('root.admin.votes',{
url : '/votes/:id',
templateUrl : 'src/admin/votes/votes.html',
controller : 'votesController'
})
.state('root.wall',{
url : '/wall/:eventId',
templateUrl : 'src/wall/wall.html',
controller: 'wallController'
})
.state('root.vote',{ //display vote for conference. integration in powerpoint.
url : '/vote/:voteId',
templateUrl : 'src/vote/vote.html',
controller : 'voteController'
})
.state('root.adminboard',{
url : '/adminboard',
templateUrl : 'src/adminboard/adminboard.html',
controller : 'adminBoardController'
});
$urlRouterProvider.otherwise('/admin/events'); //redirect. default to events page.
}])//restangular
.config(['RestangularProvider',function(RestangularProvider) {
"use strict";
RestangularProvider
.setBaseUrl('/api/v1/')
.setRestangularFields({
id: "_id"
})
.setDefaultHeaders({'Content-Type': 'application/json'})
.setRequestInterceptor(function(elem, operation, what) {
if (operation === 'put' || operation === 'post') {
elem._id = undefined;
elem.__v = undefined;
return elem;
}
return elem;
});
}]).run(['Restangular', '$window','socketService', function(Restangular, $window, socketService ){
'use strict';
Restangular.extendModel('events', function(model) {
if(typeof model !== 'object'){ //todo sometimes ( reset ) gives back a non object.
return false;
}
model.isStarted = function() { //adds started method to all events objects.
return (this.startedUntil ? ( (new Date(this.startedUntil).getTime() > Date.now())) : false);
};
model.hasMessages = function(){
return model.config.phone ||((model.counts.sms + model.counts.appli + model.counts.admin) > 0);
};
model.hasPhone = function(){
return (typeof model.config.phone === 'string');
};
model.hasFacebook = function(){
return model.config.facebookAccounts;
};
model.hasTweeter = function(){
return model.config.twitterHashtags.length;
};
model.hasInstagram = function(){
return model.config.instagramHashtags.length;
};
return model;
});
Restangular.extendModel('users', function(model){ //if user has trial offer and event is started.
model.isTrial = function(){
_.filter(model.offers,function(offer){ //todo make this a function of user? (isTrial)
return (offer.type === 'trial' && (new Date(offer.until).getTime() > Date.now()) );
});
};
return model;
});
Restangular.setErrorInterceptor(
function(response, deferred, responseHandler) {
if (response.status === 401) {
console.log("Login required... ");
$window.location.href = '/login';
} else if (response.status === 404) {
console.log("Resource not available...");
} else if (response.status === 500) {
console.log("Response received with HTTP error code: " + response.status );
return true;
} else if (response.status === 403){
return true;
}
return false; // stop the promise chain
}
);/*.setDefaultRequestParams({ socketId : socketService.socket.id});*/
}]).run(['$rootScope','$modal',function($rootScope, $modal){
"use strict";
/**
* Listen to the `$stateChangeStart` event
*/
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
//if the new state is not "terms", then ignore it
switch(toState.name){
case 'purchaseCredit' :
// console.warn('opencredit!');
$modal.open({
templateUrl : 'src/shared/purchase-credit-modal/purchase-credit-modal.html',
controller : 'purchaseModalController',
resolve : {
user : function(){return toParams.user; }
}
});
break;
case 'slideShowSettings' :
//console.error('look here toparams',toParams);
$modal.open({
templateUrl : 'src/wall/slideshow/slideshow-settings-modal.html',
controller : 'slideshowSettingsController',
size:'sm'
});
break;
case 'messagesSettings' :
$modal.open({
templateUrl : 'src/wall/messages/messages-settings-modal.html',
controller : 'messagesSettingsController',
size:'sm'
});
break;
default : //its not a modal state.
return;
}
event.preventDefault(); //prevent transition to the modal's state.
});
}]).controller('HelloWorldController', ['$scope', function($scope) {
"use strict";
$scope.greeting = 'Hello World!';
}]);
And here is my constant-app.js content :
angular.module('app', ['ngSanitize', 'ngCookies', 'ngAnimate', 'ui.router', 'highcharts-ng', 'restangular', 'FBAngular', 'ngDroplet', 'ngTagsInput', 'ui.bootstrap', 'ngDroplet', 'frapontillo.bootstrap-switch', 'timer'])
.constant('App.constants.version', '0.2.0');
what could cause this error? im stuck since several days. I tryed commenting out things but error comes back.
Related
I am trying to dynamically load BOTH a template and controller based on the route (in Angular 1.6), pulling from the current directory architecture.
app
|__login.module.js
|__home.controller.js
|__login.factory.js
|__home.view.html
|__404.view.html
|__index.html
Currently, the below code works to pull the proper template, but the controller won't load:
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
function getController(routeParams){
//I think I need a promise here, but I don't know how to write it
routeParams = routeParams.route.split('/').join('.');
return routeParams + 'controller';
}
$routeProvider.when('/:route*', {
controller: function($routeParams) { //does not work
return getController($routeParams);
},
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
I understand that controllers need to be present at the start of the app, but I am unable to write a proper resolve with a promise statement.
Can someone help me right a resolve with a simple promise that returns a string of the controller name based on the route?
I was able to get it working by not including the controller in the routing at all. Instead I put the ng-controller attribute in the view I was loading.
This worked!
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
$routeProvider.when('/:route*', {
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
In the HTML of that view, I just put ng-controller="home.controller"(or whatever controller is appropriate)
I have a page HTML that has a button "alta", when I click that button it shows an other template as a popup and in this popup, I need values of the first page fields.
here is the function of the button "alta" in the first controller:
function altaFiltro(){
//pop up
alert(vm.filtros.codigo);
$uibModal.open({
templateUrl : 'app/entities/peticion/altaFiltro.html',
size : 'md', // sm, md, lg
controller: "FiltrosCtrl",
controllerAs : 'fil',resolve: {
filtrosVm : function() {
return vm.filtros.codigo
}
}
});
}
in the controller "FiltrosCtrl" of my template model i have:
angular.module('mecenzApp').controller('FiltrosCtrl', FiltrosCtrl);
FiltrosCtrl.$inject = [ '$scope','$uibModalInstance','Filtros'];
function FiltrosCtrl($scope, $uibModalInstance,Filtros, filtrosVm) {
var fil = this;
fil.cancelar = cancelar;
function cancelar() {
$uibModalInstance.close();
};
fil.guardar = guardar;
function guardar(){
alert(filtrosVm);
if(fil.filtros.nombre!=null){
Filtros.update(fil.filtros);
$uibModalInstance.close();
}
}
}
so I want to get the vm.filtros.codigo value but it gives me an error saying that it's not defined and this is normal because it is not defined in this sub-controller (if I can call it like that)
You could use the resolve property to solve this.
$uibModal.open({
templateUrl : 'app/entities/peticion/altaFiltro.html',
size : 'md', // sm, md, lg
controller: "FiltrosCtrl",
controllerAs : 'fil',
resolve: {
filtrosVm : function() {
return vm.filtros.codigo
}
}
});
Then filtrosVm will appear as a dependency for your Modals's controller.
function FiltrosCtrl($scope, $uibModalInstance,Filtros, filtrosVm) {
var fil = this;
fil.cancelar = cancelar;
function cancelar() {
$uibModalInstance.close();
};
fil.guardar = guardar;
function guardar(){
alert(filtrosVm);
if(fil.filtros.nombre!=null){
Filtros.update(fil.filtros);
$uibModalInstance.close();
}
}
}
You pass items to the modal instance by using resolve:
Much like this:
resolve: {
Filtros: function () {
return $scope.Filtros;
}
}
Here is a Plunk that does that
finaly it works now i get 2 fields values here is the code:
parent controller:
vm.altaFiltro = altaFiltro;
function altaFiltro(){
//pop up
alert(vm.filtros.codigo+"/iniciativa="+vm.filtros.nombreinic);
$uibModal.open({
templateUrl : 'app/entities/peticion/altaFiltro.html',
size : 'md', // sm, md, lg
controller: "FiltrosCtrl",
controllerAs : 'vm',
resolve : {
codigo : function() {
return vm.filtros.codigo;
} ,
iniciativa : function() {
return vm.filtros.nombreinic;
} ,
}
});
}
model controller:
FiltrosCtrl.$inject = [ '$scope','$uibModalInstance','Filtros','codigo','iniciativa'];
function FiltrosCtrl($scope, $uibModalInstance, Filtros,codigo,iniciativa) {
var vm = this;
vm.cancelar = cancelar;
function cancelar() {
$uibModalInstance.close();
};
vm.guardar = guardar;
function guardar(){
alert("GUARDAR:"+codigo+"/iniciativa="+iniciativa);
vm.filtros.codigo = codigo;
vm.filtros.nombreinic = iniciativa;
if(vm.filtros.nombre!=null){
Filtros.update(vm.filtros);
$uibModalInstance.close();
}
}
}
Thank you so much guys !
I want to set default language by user country, but i cannot set preferredLanguage in $.get. I am using "http://ipinfo.io". Is there any other way to set default language?
var app = angular.module('test', ['pascalprecht.translate'])
.config(function config($translateProvider, $translatePartialLoaderProvider) {
$translateProvider
.translations('en', {
TRANLATION : 'Translation',
BUTTON_LANG_EN : 'English',
BUTTON_LANG_SK : 'Slovak',
HOME: 'Home',
})
.translations('sk', {
TRANLATION : 'Preklad',
BUTTON_LANG_EN : 'Anglicky',
BUTTON_LANG_SK : 'Slovensky',
HOME: 'Zakladne informacie',
});
$.get("http://ipinfo.io", function(response) {
if(response.country == 'SK'){
$translateProvider.preferredLanguage('sk');
}else{
$translateProvider.preferredLanguage('en');
}
}, "jsonp");
});
You are probably running in an async issue, so, when the ajax call $.get (assuming is jQuery) is resolved you are out from the config phase of angular js...
Try something like that:
in app.js
var app = angular.module('langTest', ['pascalprecht.translate','calsethTranslate'])
.config(function($injector, $translateProvider){
jQuery
.when({})
.then(function() {
return $.get('http://ipinfo.io', function(response) {
return response;
},'jsonp')
})
.then(function(response) {
var lang = response.country === 'SK' ? 'SK' : 'EN';
var _$injector = angular.element(document.body).injector();
console.log(lang);
if (_$injector.has('$translate')) {
console.log("has "+lang);
return _$injector.get('$translate').use(lang);
}
})
});
On server side i have a next method, which check if token found in database:
def method(token)
if (Database.find(token).length == 0)
not_found()
else
success()
end
url as token/:token, for example token/123
I have a state for it:
$stateProvider.state('token', {
url: '/token/:token',
templateUrl: 'success'
}).state('404', {
url: '/404',
templateUrl: 'notfound'
});
But i do not know, how to in ui router check token, i need some like this
$http.post('/token', {token: $stateParams.token}).success(function(){
//ok continue and load `success` template
}).error(function(){
$state.go('404'); //when error
});
Is it possible with ui router?
I also had the same situation, This is what I did
.when('/beacon/:beacon_id',{
templateUrl : 'components/beacon/beacon.html',
controller : 'beaconController',
access : { requiredLogin: true },
resolve : {
Beacon : ['$route', 'BeaconService', function($route, BeaconService){
var beacon = BeaconService.beacon();
return beacon.get({'beacon_id':$route.current.params.beacon_id}, function(successResponse){
console.log(successResponse.result[0]);
return successResponse.result[0];
}, function(errorResponse){
$location.path('blablabla'); // This will redirect me to 404. :P
});
}]
}
})
.otherwise({templateUrl : '404.html'});
In controller
App.controller('beaconCtrl', ['Beacon', '$scope', function(Beacon, $scope){
//Get Beacon into controller than get your promise.
Beacon.$promise.then(function(data){
$scope.beacon = data.result[0];
});
}]);
I have an application in angularjs where each controller is in written in different JS files.
I need to call those files only on routechange event. For now I am successful in getting the appropriate controller file, but for some reason its throwing error:
Error: [ng:areq] Argument 'ApplicantsController' is not a function, got undefined
http://errors.angularjs.org/1.2.25/ng/areq?p0=ApplicantsController&p1=not%20a%20function%2C%20got%20undefined
minErr/<#http://localhost/talentojo/app/js/angularjs/angular.js:78:5
assertArg#http://localhost/talentojo/app/js/angularjs/angular.js:1509:5
assertArgFn#http://localhost/talentojo/app/js/angularjs/angular.js:1520:76
$ControllerProvider/this.$get</<#http://localhost/talentojo/app/js/angularjs/angular.js:7278:9
nodeLinkFn/<#http://localhost/talentojo/app/js/angularjs/angular.js:6670:13
forEach#http://localhost/talentojo/app/js/angularjs/angular.js:332:11
nodeLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6657:11
compositeLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6105:13
publicLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6001:30
z/<.link#https://code.angularjs.org/1.2.25/angular-route.min.js:7:388
nodeLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6712:1
compositeLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6105:13
publicLinkFn#http://localhost/talentojo/app/js/angularjs/angular.js:6001:30
createBoundTranscludeFn/boundTranscludeFn#http://localhost/talentojo/app/js/angularjs/angular.js:6125:1
controllersBoundTransclude#http://localhost/talentojo/app/js/angularjs/angular.js:6732:11
v#https://code.angularjs.org/1.2.25/angular-route.min.js:6:355
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost/talentojo/app/js/angularjs/angular.js:12980:15
l/<#https://code.angularjs.org/1.2.25/angular-route.min.js:11:127
qFactory/defer/deferred.promise.then/wrappedCallback#http://localhost/talentojo/app/js/angularjs/angular.js:11572:15
qFactory/defer/deferred.promise.then/wrappedCallback#http://localhost/talentojo/app/js/angularjs/angular.js:11572:15
qFactory/ref/<.then/<#http://localhost/talentojo/app/js/angularjs/angular.js:11658:11
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost/talentojo/app/js/angularjs/angular.js:12701:9
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost/talentojo/app/js/angularjs/angular.js:12513:15
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost/talentojo/app/js/angularjs/angular.js:12805:13
done#http://localhost/talentojo/app/js/angularjs/angular.js:8378:34
completeRequest#http://localhost/talentojo/app/js/angularjs/angular.js:8592:7
createHttpBackend/</xhr.onreadystatechange#http://localhost/talentojo/app/js/angularjs/angular.js:8535:1
My code:
HTML
<body>
<!-- Header Starts -->
<div ng-include="'assets/defaults/header.html'"></div>
<!-- Header Ends -->
<ul>
<li>
Home
</li>
<li>
Applicants
</li>
</ul>
<div ng-view></div>
<!-- Footer Starts -->
<div ng-include="'assets/defaults/footer.html'"></div>
<!-- Footer Ends -->
</body>
Route:
var app = angular.module('TOJO',['ngRoute']);
app.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl : 'assets/home.html',
controller : 'HomeController'
}).when('/applicants', {
templateUrl : 'assets/applicants/list.html',
scriptUrl : 'assets/applicants/applicants.js'
});
}).
run(function($rootScope, $location) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if(next.scriptUrl !== undefined)
loadScript(next.scriptUrl);
});
});
app.controller('HomeController', function($scope) {
$scope.message = 'Look! I am home page.';
});
var loadScript = function(url, type, charset) {
if (type===undefined) type = 'text/javascript';
if (url) {
var script = document.querySelector("script[src*='"+url+"']");
if (!script) {
var heads = document.getElementsByTagName("head");
if (heads && heads.length) {
var head = heads[0];
if (head) {
script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', type);
if (charset) script.setAttribute('charset', charset);
head.appendChild(script);
}
}
}
return script;
}
};
And the file applicants.js which is getting called on route change:
app.controller('ApplicantsController',['$scope', function($scope) {
$scope.message = 'Look! I am home page.';
}
]);
list.html:
<div ng-controller="ApplicantsController">{{message}}</div>
Had you already a look, into: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider resolve event?
"If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated." -> Maybe you can insert your script here into the body / head tag and return a promise.
I use this to include stylesheets e.g.
resolve: {
style: function () {
angular.element('head').append('<link href="*.css" rel="stylesheet">');
}
}
So finally I found the solution:
I used resolve, to add script in my document dynamically. So my route:
var app = angular.module('TOJO',['ngRoute']).service('HttpTojoService', Service);
app.config(function($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controllerProvider = $controllerProvider;
app.compileProvider = $compileProvider;
app.routeProvider = $routeProvider;
app.filterProvider = $filterProvider;
app.provide = $provide;
$routeProvider.when('/', {
templateUrl : 'assets/home.html',
controller : 'HomeController'
}).when('/applicants', {
templateUrl : 'assets/applicants/list.html',
controller : 'ApplicantsController',
resolve:{deps:function($q, $rootScope){
return routeResolver($q.defer(),['assets/applicants/applicants.js'],$rootScope);
}}
}).when('/jobs', {
templateUrl : 'assets/jobs/list.html',
controller : 'JobsController',
resolve:{deps:function($q, $rootScope){
return routeResolver($q.defer(),['assets/jobs/jobs.js'],$rootScope);
}}
});
});
function routeResolver(deferred,dependencies,$rootScope){
$script(dependencies, function()
{
$rootScope.$apply(function()
{
deferred.resolve();
});
});
return deferred.promise;
}
and my controller:
app.controllerProvider.register('ApplicantsController',['$scope', 'HttpTojoService', function($scope, HttpTojoService) {
$scope.message = 'Look! I am applicants page.';
}
]);
And also you'll also need scripts.js