Use require.js with angular.js - javascript

I am new in require.js, I am implementing requier.js with angular.js, but i got error. Here is my code:
config file:
require.config({
paths: {
angular: 'https://code.angularjs.org/1.5.5/angular.min',
angularRoute: '//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.min',
angularAnimate: '//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min',
},
shim: {
'angular' : {'exports' : 'angular'},
'angularRoute': ['angular'],
'angularAnimate': ['angular']
},
priority: [
"angular"
],
});
require([
'angular',
'app',
'controllers/first-controller',
'controllers/second-controller',
'controllers/third-controller',
'services/services',
'directives/directives'
], function(angular, app) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['WalletHubApp']);
});
}
);
This is my app file:
define(['angular'], function (angular) {
var app = angular.module('app', ['ui.router','ngAnimate']);
WalletHubApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/walletHub/1/');
$stateProvider
.state('test', {
url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
templateUrl: function ($stateParams){
return "templates/"+$stateParams.id + '.html';
},
controllerProvider: function($stateParams) {
console.log($stateParams)
var ctrlName = $stateParams.id + "Controller";
return ctrlName;
}
});
});
return app;
});
This is Controller File:
define(['app'], function(app) {
WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
$http.get('sample.json')
.then(function(res){
$scope.persons = res.data
});
var parts = $stateParams.folderPath.split('/')
$scope.params = false;
if(parts[0] != "")
{
$scope.parts = parts;
$scope.params = true;
}
})
return;
});
I dont know what is wrong in this code.Please help me to sort out this

According to official document
It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names.
// in app.js file, remove module name :
define(["angular", "angularRoute","angularAnimate"], function(angular) {
var WalletHubApp = angular.module('WalletHubApp', ['ui.router','ngAnimate']);
WalletHubApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/walletHub/1/');
$stateProvider
.state('test', {
url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
templateUrl: function ($stateParams){
return "templates/"+$stateParams.id + '.html';
},
controllerProvider: function($stateParams) {
console.log($stateParams)
var ctrlName = $stateParams.id + "Controller";
return ctrlName;
}
});
});
return WalletHubApp;
});
// in controller file change WalletHubApp to app
define(['app'], function(WalletHubApp) {
WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
$http.get('sample.json')
.then(function(res){
$scope.persons = res.data
});
var parts = $stateParams.folderPath.split('/')
$scope.params = false;
if(parts[0] != "")
{
$scope.parts = parts;
$scope.params = true;
}
})
return;
});

Related

Add jQuery dependency in angularJs

How I can add jquery-ui.js to my controller.I'm new to the ui-router
.state('new_patient', {
url: '/newpatient',
templateUrl: window.localStorage.getItem('contextPath') + '/module/laboratory/newpatient',
controller: 'PatientController',
resolve: {
deps: function($q, $rootScope) {
var deferred = $q.defer();
var dependencies = ['jquery-ui'];
require(dependencies, function() {
$rootScope.$apply(function() {
deferred.resolve();
});
});
return deferred.promise;
}
}
});
OR as follows
resolve: { async: ['jquery-ui', function($) {
}]
}
pls help..
Its for working of an accordion.. Thanks in advance for replies.
.state('new_patient', {
url: '/newpatient',
templateUrl: window.localStorage.getItem('contextPath') + '/module/laboratory/newpatient',
controller: 'PatientController',
resolve: {
deps: function ($q){
var defer = $q.defer();
require(['js/core/jquery-ui'], function() {
defer.resolve();
});
return defer.promise;
}
}
});

Retrieving cookie with every load of Single Page App

What specific changes need to be made to the AngularJS code below to check for the existence of a cookie named myCookie every time a page is loaded, and then to set the $rootScope.myCookieValue variable to become the value of myCookie?
The code is from the sample app whose complete code you can explore at this link. It is a very simple example app, and I just want a simple working solution to this so that I can build up more complex approaches from it.
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).controller('navigation',
function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function() {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function($http) {
var self = this;
$http.get('resource/').then(function(response) {
self.greeting = response.data;
})
});
you can do it in run block I guess:
angular.module('hello', ['ngCookies', 'ngRoute'])
.config(function ($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'home',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).run(function ($rootScope, $cookies) {
var cookieValue = $cookies.get("myCookie");
if (cookieValue) {
$rootScope.myCookieVar = cookieValue;
}
}).controller('navigation',
function ($rootScope, $http, $location, $route) {
var self = this;
self.tab = function (route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function (response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function () {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function () {
$http.post('logout', {}).finally(function () {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function ($http) {
var self = this;
$http.get('resource/').then(function (response) {
self.greeting = response.data;
})
});
I think you should use angular version > 1.4.x
you should also add reference angular-cookies.js

Issue on access a service in a ui-router controller

I am having issues trying to access a service on a controller. The issue happen when the Ordenes services is called. How I can call a service with two parameter using values from the scope from a controller using ui-router?
I have the same code working but without the use of ui-router. It seems like the code is not loading properly the service inside the Controller.
App.js
'use strict';
app = angular.module('logica-erp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'authorization',
'ui.router.stateHelper',
'logica-erp.kds',
'logica-erp.pos'
])
app.run(function($rootScope) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
});
app.config(function ($stateProvider, $urlRouterProvider) {
//delete $httpProvider.defaults.headers.common['X-Requested-With'];
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'views/main.html',
controller:'MainCtrl'
})
.state('comanda', {
url: '/comanda',
templateUrl: 'views/comanda.html',
controller:'ComandaCtrl'
})
.state('counter', {
url: '/counter',
templateUrl: 'views/counter.html',
controller:'CounterCtrl'
})
})
comanda.js
(function() {
'use strict';
var app;
app = angular.module('logica-erp.kds', ['timer', 'logica-erp.service.pos']);
this.ComandaCtrl = [
'$scope', '$interval', 'Ordenes', function($scope, $interval, Ordenes) {
var error, stop, success, tick;
$scope.tiempos = [
{
name: '15 seg',
value: 15000
}, {
name: '30 seg',
value: 30000
}, {
name: '60 seg',
value: 60000
}, {
name: '120 seg',
value: 120000
}
];
$scope.selected_tiempo = $scope.tiempos[1];
$scope.tipos = [
{
name: 'Alimentos',
value: 'a'
}, {
name: 'Bebidas',
value: 'b'
}, {
name: 'Todos',
value: ''
}
];
$scope.selected_tipo = $scope.tipos[2];
success = function(result) {
if (angular.toJson(result) !== angular.toJson($scope.ordenes)) {
$scope.isLoading = true;
$scope.ordenes = result;
console.log(JSON.stringify($scope.ordenes));
}
return $scope.isLoading = false;
};
error = function(error) {
console.log('error ' + error);
return $('#modal').foundation('open');
};
tick = function() {
$scope.platos = Ordenes.query({
tipo: $scope.selected_tipo.value,
sucursal: 2
});
return $scope.platos.$promise.then(success, error);
};
tick();
stop = $interval(tick, $scope.selected_tiempo.value);
$scope.change_refresh = function() {
$interval.cancel(stop);
return stop = $interval(tick, $scope.selected_tiempo.value);
};
return $scope.update_order = function(mesa, aaybb_id) {
return angular.forEach($scope.ordenes.mesas, function(orden) {
if (orden.mesa === mesa) {
return angular.forEach(orden.aaybb, function(aaybb) {
if (aaybb._id === aaybb_id) {
if (aaybb.estatus === 'ASIGNADO') {
aaybb.estatus = 'EN PROCESO';
} else if (aaybb.estatus === 'EN PROCESO') {
aaybb.estatus = 'PREPARADO';
$('#timer_' + aaybb._id)[0].stop();
}
return Ordenes.update(aaybb);
}
});
}
});
};
}
];
app.controller('ComandaCtrl', ComandaCtrl);
}).call(this);
Console log
Error: value is undefined
extractParams/<#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:344:11
forEach#http://127.0.0.1:9000/bower_components/angular/angular.js:336:11
extractParams#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:343:9
ResourceFactory/</Resource[name]#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:398:39
this.ComandaCtrl</tick#http://127.0.0.1:9000/scripts/controllers/comanda.js:72:25
this.ComandaCtrl<#http://127.0.0.1:9000/scripts/controllers/comanda.js:78:7
I fixed the issue, it was a old bug in the angular-resource lib. I didn't know but my bower was installing version 1.0.7 :S anyway; this was very annoying.

AngularJS - Unknown provider: AuthProvider

I am trying to redirect users to a login page if they make an attempt to access pages that require them to be logged in. I am using Firebase and AngularJS, following this guide. The error explanation on the AngularJS site indicates that either a non-existent definition or duplicate definition is causing the issue but I cannot identify either of these in my code. Additionally, the stack trace of the error doesn't indicate which of my files caused the error, only mentioning the angular.js file.
Can anyone give me some insight as to what is causing this issue?
Note: The site runs without errors and users can log in and out if I leave out the resolve section of the $routeProvider.
Here is my app.js
angular.module('richWebApp', ['ngRoute', 'firebase', 'objectFilter'])
.constant('fb', {
url: 'https://<my-firebase-app>.firebaseio.com/' //name removed for security reasons
})
.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if(error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
})
.config(function($routeProvider){
$routeProvider.
when('/login', {
templateUrl: 'pages/login/login.html'
}).
when('/main', {
templateUrl: 'pages/main/main.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
when('/thread/:threadId', {
templateUrl: 'pages/thread/thread.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
otherwise({
redirectTo: '/login'
});
});
Here is the main.js controller
angular.module('richWebApp')
.controller('mainPageController', function($scope, $location, userService, currentAuth, threadService, fb, $firebaseAuth, $filter){
$scope.user = userService.getLoggedInUser();
$scope.newThreadTitle = '';
$scope.threadSubject = ''
$scope.createNewThread = false;
$scope.sortBy = 'dateAdded'
$scope.threads = threadService.getAllThreads();
$scope.getSubjects = function(subject) {
return $scope.threads.subject;
}
$scope.beginAddThread = function() {
$scope.createNewThread = true;
}
$scope.addThread = function(){
if(!$scope.newThreadTitle || !$scope.newThreadSubject){
return false;
}
var date = new Date();
var newThread = {
title: $scope.newThreadTitle,
subject: $scope.newThreadSubject,
username: $scope.user.name,
numComments: 0,
comments: [],
dateAdded: date.getTime()
};
$scope.threads.$add(newThread);
$scope.newThread = '';
$scope.newThreadTitle = '';
$scope.newThreadSubject = '';
$scope.createNewThread = false;
}
$scope.sortByDate = function() {
$scope.sortBy = 'dateAdded';
}
$scope.sortByPopularity = function() {
$scope.sortBy = 'numComments';
}
$scope.searchSubject = function(subject) {
$scope.searchThread = subject;
}
$scope.logout = function(){
userService.logout();
}
});
Here is the thread.js controller
angular.module('richWebApp')
.controller('threadPageController', function($scope, $location, $routeParams, $filter, currentAuth, threadService, fb, userService){
var threadId = $routeParams.threadId;
$scope.newComment = '';
var thread = threadService.getThread(threadId);
thread.$bindTo($scope, 'thread')
$scope.addComment= function(){
if(!$scope.newComment){
return false;
}
var currentUser = userService.getLoggedInUser();
var date = new Date();
var newComment = {
text: $scope.newComment,
username: currentUser.name,
dateAdded: date.getTime(),
userPic: currentUser.profilePic
};
$scope.thread.comments = $scope.thread.comments || [];
$scope.thread.comments.push(newComment);
$scope.thread.numComments += 1;
$scope.newComment = '';
}
});
Your code is referring to an Auth factory, which is shown in the example under Retrieving Authentication State. Include this in your code.
.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("<YOUR FIREBASE>");
return $firebaseAuth(ref);
}
]);

AngularJS: lazy loading controllers and content

In this simplified scenario, I have two files: index.htm, lazy.htm.
index.htm:
var myApp = angular.module('myApp', []);
myApp.controller('embed',function($scope){
$scope.embed = 'Embedded Controller';
});
<div ng-controller="embed">{{embed}}</div>
<div ng-include="'lazy.htm'"></div>
lazy.htm
myApp.controller('lazy',function($scope){
$scope.lazy = 'Lazy Controller';
});
<div ng-controller="lazy">
{{lazy}}
</div>
The result is an error: "Argument 'lazy' is not a function, got undefined"
Using a function instead
lazy.htm
function lazy($scope) {
$scope.lazy = 'Lazy Controller';
}
<div ng-controller="lazy">
{{lazy}}
</div>
This works until version 1.3 beta 14. In beta 15 was removed the global controller functions: https://github.com/angular/angular.js/issues/8296
So now, what is the better way to get angularized contents of lazy.htm dynamically?
UPDATE:
In this article (http://ify.io/lazy-loading-in-angularjs) I found another possible solution. The $controllerProvider allow us to register new controllers after angular bootstrap. Works like a charm. Tested in v1.3.0-beta.18
index.htm:
var myApp = angular.module('myApp', [])
.controller('embed',function($scope){
$scope.embed = 'Embedded Controller';
})
.config(function($controllerProvider) {
myApp.cp = $controllerProvider;
});
<div ng-controller="embed">{{embed}}</div>
<div ng-include="'lazy.htm'"></div>
lazy.htm
myApp.cp.register('lazy',function($scope){
$scope.lazy = 'Lazy Controller';
});
<div ng-controller="lazy">
{{lazy}}
</div>
UPDATE 2:
Two other alternatives that works are:
lazy.htm
_app = $('[ng-app]').scope();
_app.lazy = function($scope) {
$scope.lazy = 'Lazy Controller';
};
OR
var $rootScope = $('[ng-app]').injector().get('$rootScope');
$rootScope.lazy = function($scope) {
$scope.lazy = 'Lazy Controller';
};
But I believe these last two examples should not be used in production.
You can also use the jquery with the resolve the $routeProvider
app.js
/* Module Creation */
var app = angular.module ('app', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript('js/controllers/'+name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/', {
templateUrl: 'views/foo.html',
resolve: loader(['foo'])
})
.when('/bar',{
templateUrl: 'views/bar.html',
controller: 'BarCtrl',
resolve: loader(['bar'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
/views/foo.html
<section ng-controller='FooCtrl'>
{{text}}
</section>
js/controllers/foo.js
/*Here we use the synthesized version of $controllerProvider.register
to register the controller in view*/
app.registerCtrl('FooCtrl',function($scope){
$scope.text = 'Test';
});
/views/bar.html
<section>
{{text2}}
</section>
js/controllers/bar.js
app.registerCtrl('BarCtrl',function($scope){
$scope.text2 = 'Test';
});
////JConfig file--------
window.angularApp.config(function ($routeProvider,$controllerProvider,$compileProvider,$provide, azMessages) {
$routeProvider.when('/login', {
resolve: {
load: ['$q', '$rootScope', function ($q, $rootScope) {
var deferred = $q.defer();
require([
//load required Js file here
], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
} ]
}
});
$routeProvider.otherwise({ redirectTo: '/login' });
window.angularApp.components = {
controller: $controllerProvider.register,
service: $provide.service,
directive: $compileProvider.directive
}
//contoller declaration
angularApp.components.controller('DiscussionController',[function(){
}]);
At first I utilized André Betiolo's answer. However, it does not always work becasue the ajax loading is non-blocking causing the view to sometimes request the controller prior to the script being loaded.
As a solution i forced the function not to return until all scripts successfully loaded. This is kind of hackish but makes sure the loads are successful prior to completing the resolve. It also allows for loading of multiple controllers.
app.js
var app = angular.module ('app', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
//jquery to dynamically include controllers as needed
function controllers(controllers){
var numLoaded = 0;
for (i = 0; i < controllers.length; i++) {
$.ajaxSetup({async:false});
$.getScript('js/controllers/' + controllers[i] + '.js').success(function(){
numLoaded++;
if (numLoaded == controllers.length) {
return true; //only return after all scripts are loaded, this is blocking, and will fail if all scripts aren't loaded.
}
});
}
}
$routeProvider
.when('/', {
templateUrl: 'views/foo.html',
resolve: {
load: function () {
controllers(['foo'])
}
}
})
.when('/bar',{
templateUrl: 'views/bar.html',
controller: 'BarCtrl',
resolve: {
load: function () {
controllers(['bar','foo']) //you can load multiple controller files
}
}
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
/views/foo.html
<section ng-controller='FooCtrl'>
{{text}}
</section>
/views/bar.html
<section ng-controller='BarCtrl'>
{{text2}}
</section>
<section ng-controller='FooCtrl'>
{{text}}
</section>
/controllers/bar.js
app.registerCtrl('BarCtrl',function($scope){
$scope.text2 = 'Test';
});
You can have pure AngularJS lazy loading.
Create "LazyService":
var ng = angular.module('app');
ng.factory('lazyService', [ '$http', function($http) {
var jsPath = 'js/${ name }.js';
var promisesCache = {};
return {
loadScript: function(name) {
var path = jsPath.replace('${ name }', name);
var promise = promisesCache[name];
if (!promise) {
promise = $http.get(path);
promisesCache[name] = promise;
return promise.then(function(result) {
eval(result.data);
console.info('Loaded: ' + path);
});
}
return promise;
}
}
}]);
Then, define your config:
var ng = angular.module('app', [ 'ngRoute' ]);
ng.config([ '$routeProvider', '$controllerProvider', '$provide', function($routeProvider, $controllerProvider, $provide) {
// Lazy loading
ng.lazy = {
controller: $controllerProvider.register,
//directive: $compileProvider.directive,
//filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
}
$routeProvider
.when('/', {
templateUrl: 'view/home.html'
})
.when('/vendor', {
templateUrl: 'view/vendor.html',
resolve: {
svc: [ 'lazyService', function(lazyService) {
return lazyService.loadScript('services/vendor');
}],
ctrl: [ 'lazyService', function(lazyService) {
return lazyService.loadScript('controllers/vendor');
}]
}
});
. . .
On "js/services/vendor.js", create service as:
var ng = angular.module('app');
ng.lazy.service('vendorService', [ function() {
. . .
On "js/controllers/vendor.js", create controller as:
var ng = angular.module('app');
ng.lazy.controller('vendorController', [ function() {
. . .
The "resolve" property on when defines which promises should be resolved before route loads.
The best way to do what you are asking is to instead use a directive and tie the controller and template together that way so its bound at the appropriate time. Currently, the binding it not happening in lazy.htm at the right time unless you declare a global function as you've shown in your second example.
Ideally - Angular will force you to separate HTML and JS as in newer versions this may be enforced more often.
You may have to use requireJS
http://solutionoptimist.com/2013/09/30/requirejs-angularjs-dependency-injection/
For the sake of trick can you try
ng-controller-controller="'lazy'"
or
In HTML
ng-controller-controller="myObject.controller"
Somewhere inject
$scope.myObject.controller = $controller('lazy', {$scope: $scope})
Try this ARI plugin for Angular JS. It helps you to lazy load the controller scripts on demand.
You also can use Directives to load your controller!
A example here:
https://gist.github.com/raphaelluchini/53d08ed1331e47aa6a87
I am sending you sample code. It is working fine for me. So please check this:
var myapp = angular.module('myapp', ['ngRoute']);
/* Module Creation */
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function ($routeProvider, $controllerProvider) {
app.register = {
controller: $controllerProvider.register,
//directive: $compileProvider.directive,
//filter: $filterProvider.register,
//factory: $provide.factory,
//service: $provide.service
};
// so I keep a reference from when I ran my module config
function registerController(moduleName, controllerName) {
// Here I cannot get the controller function directly so I
// need to loop through the module's _invokeQueue to get it
var queue = angular.module(moduleName)._invokeQueue;
for (var i = 0; i < queue.length; i++) {
var call = queue[i];
if (call[0] == "$controllerProvider" &&
call[1] == "register" &&
call[2][0] == controllerName) {
app.register.controller(controllerName, call[2][1]);
}
}
}
var tt = {
loadScript:
function (path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else {
result.resolve();
}
}
};
script.onerror = function () { result.reject(); };
document.querySelector(".shubham").appendChild(script);
return result.promise();
}
}
function stripScripts(s) {
var div = document.querySelector(".shubham");
div.innerHTML = s;
var scripts = div.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
return div.innerHTML;
}
function loader(arrayName) {
return {
load: function ($q) {
stripScripts(''); // This Function Remove javascript from Local
var deferred = $q.defer(),
map = arrayName.map(function (obj) {
return tt.loadScript(obj.path)
.then(function () {
registerController(obj.module, obj.controller);
})
});
$q.all(map).then(function (r) {
deferred.resolve();
});
return deferred.promise;
}
};
};
$routeProvider
.when('/first', {
templateUrl: '/Views/foo.html',
resolve: loader([{ controller: 'FirstController', path: '/MyScripts/FirstController.js', module: 'app' },
{ controller: 'SecondController', path: '/MyScripts/SecondController.js', module: 'app' }])
})
.when('/second', {
templateUrl: '/Views/bar.html',
resolve: loader([{ controller: 'SecondController', path: '/MyScripts/SecondController.js', module: 'app' },
{ controller: 'A', path: '/MyScripts/anotherModuleController.js', module: 'myapp' }])
})
.otherwise({
redirectTo: document.location.pathname
});
}])
And in HTML Page:
<body ng-app="app">
<div class="container example">
<!--ng-controller="testController"-->
<h3>Hello</h3>
<table>
<tr>
<td>First Page </td>
<td>Second Page</td>
</tr>
</table>
<div id="ng-view" class="wrapper_inside" ng-view>
</div>
<div class="shubham">
</div>
</div>
Thank U

Categories