AngularJS controller is not a function - javascript

I can't find the mistake in my application.
The error stack that i receive is this one:
Error: [ng:areq] Argument 'RepoController' is not a function, got undefined
Here is the code of app.js
(function() {
var app = angular.module('gitHubViewer',["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.when("/user/:username", {
templateUrl: "user.html",
controller: "UserController"
})
.when("/repo/:usermane/:reponame", {
templateUrl: "repo.html",
controller: "RepoController"
})
.otherwise({
redirectTo:"/main"
});
});
}());
here is the code of the controller
(function() {
var module = angular.module('gitHubViewer');
var RepoController = function($scope, github, $routeParams) {
var onRepoDetailsComplete = function(data) {
$scope.issues = data;
github.getRepoCotributors($score.username, $scope.reponame).then(onRepoCotributorsComplete,onError);
};
var onRepoCotributorsComplete = function(data) {
$scope.repoContribuors = data;
};
var onError = function(reason) {
$scope.error = reason;
}
$scope.username = $routeParams.username;
$scope.reponame = $routeParams.reponame;
github.getRepoDetails($score.username, $scope.reponame).then(onRepoDetailsComplete,onError);
};
module.controller('RepoController',["$scope","github","$routeParams",RepoController]);
}());
Can you please have a look becuase I really can't find teh mistake that I made.
Regards
Fabio

Where does "$score.username" come from?
github.getRepoDetails($score.username, $scope.reponame)
I think that you are missing a dependency for the $score or you have just misspelled $scope.

Related

Error: [$injector:modulerr] with angular JS [GULP CONTEXT]

first of all , i know this error seems to be famous and i should be able to get the solution with google easily but unfortunately none of the links i read did help me to solve the problem...
I underline the fact i use gulp to minify the Javascript.
Basically this is my module:
(function () {
var app = angular.module('meanApp', ['ngRoute']);
app.config (function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/register', {
templateUrl: '/auth/register/register.view.html',
controller: 'registerCtrl',
controllerAs: 'vm'
})
.when('/login', {
templateUrl: '/auth/login/login.view.html',
controller: 'loginCtrl',
controllerAs: 'vm'
})
.when('/profile', {
templateUrl: '/profile/profile.view.html',
controller: 'profileCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
app.run(function($rootScope, $location, authentication) {
$rootScope.$on('$routeChangeStart', function(event, nextRoute, currentRoute) {
if ($location.path() === '/profile' && !authentication.isLoggedIn()) {
$location.path('/');
}
});
});
})();
authentication is the following service:
(function () {
angular
.module('meanApp')
.factory('authentication', authentication);
// $inject : To allow the minifiers to rename the function parameters and still be able to inject the right services, the function needs to be annotated with the $inject property. The $inject property is an array of service names to inject.
// https://docs.angularjs.org/guide/di
authentication.$inject = ['$http', '$window'];
function authentication ($http, $window) {
var saveToken = function (token) {
$window.localStorage['mean-token'] = token;
};
var getToken = function () {
return $window.localStorage['mean-token'];
};
var isLoggedIn = function() {
var token = getToken();
var payload;
if(token){
payload = token.split('.')[1];
payload = $window.atob(payload); //will decode a Base64 string
payload = JSON.parse(payload);
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
var currentUser = function() {
if(isLoggedIn()){
var token = getToken();
var payload = token.split('.')[1];
payload = $window.atob(payload);
payload = JSON.parse(payload);
return {
email : payload.email,
name : payload.name
};
}
};
//An interface between the Angular app and the API, to call the login and register end-points and save the returned token. This will use the Angular $http service
// strict mode :
var register = function(user) {
console.log("ARNAUD: Arriving in register promise");
return $http.post('/api/register', user).success(function(data){
saveToken(data.token);
});
};
var login = function(user) {
return $http.post('/api/login', user).success(function(data) {
saveToken(data.token);
});
};
var logout = function() {
$window.localStorage.removeItem('mean-token');
};
/* console.log("currentUser:"+currentUser);
console.log("saveToken:"+saveToken);
console.log("getToken:"+getToken);
console.log("isLoggedIn:"+isLoggedIn);
console.log("register:"+register);
console.log("login:"+login);
console.log("logout:"+logout);*/
return {
currentUser : currentUser,
saveToken : saveToken,
getToken : getToken,
isLoggedIn : isLoggedIn,
register : register,
login : login,
logout : logout
};
}
})();
A controller:
(function () {
angular
.module('meanApp')
.controller('registerCtrl', registerCtrl);
registerCtrl.$inject = ['$location', 'authentication'];
function registerCtrl($location, authentication) {
console.log("ARNAUD : inside registerCtrl, initializing the properties to empty");
var vm = this;
vm.credentials = {
name : "",
email : "",
password : ""
};
vm.onSubmit = function () {
console.log('ARNAUD : arriving in vm.Submit');
authentication
.register(vm.credentials)
.error(function(err){
alert(err);
})
.then(function(){
$location.path('profile');
});
};
}
})();
my index.html:
<!DOCTYPE html>
<html ng-app="meanApp">
<head>
<title>MEAN stack authentication example</title>
<base href="/">
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap-theme.min.css">
</head>
<body ng-view>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="app.min.js"></script>
</body>
</html>
Thanks a lot for your help
You missed to have to follow minification rule applies to DI on config & run block which should be like below. I'd suggest you to follow Inline Array Annotation method of DI which injecting dependency.
Code
(function () {
var app = angular.module('meanApp', ['ngRoute']);
app.config (['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
//code as is
}
]);
app.run(['$rootScope', '$location', 'authentication',
function($rootScope, $location, authentication) {
//code as is
}
]);
})();
See the warning specified here in DOCS

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);
}
]);

Scope not defined

angular.module('CrudApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'assets/tpl/lists.html',
controller: ListCtrl
}).
when('/add-user', {
templateUrl: 'assets/tpl/add-new.html',
controller: AddCtrl
}).
otherwise({
redirectTo: '/'
});
}]);
function ListCtrl($scope, $http) {
$http.get('api/users').success(function(data) {
$scope.users = data;
});
}
function AddCtrl($scope, $http, $location) {
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
}
// Delete user
I keep getting the error scope not defined and cannot seem to figure out why. can anybody help me troubleshoot this? All of the other functions are working except the delete customer. I don't know what is causing the error
Working Plunker
Here is it. I've updated your sintax, installed the dependencies and your $scope is working. Look at the Plunker. :)
Markup:
<body ng-app="CrudApp">
<div ng-controller="ListCtrl">
List Controller says what? {{what}}
</div>
<div ng-controller="AddCtrl">
Add Cntroller says What? {{what}}
</div>
</body>
script.js
var app = angular.module('CrudApp', ['ngRoute']);
app.controller('ListCtrl', function ($scope, $http) {
$scope.what = 'Rodrigo souza is beauty';
$http.get('api/users').success(function(data) {
$scope.users = data;
});
});
app.controller('AddCtrl', function ($scope, $http, $location) {
$scope.what = 'Rodrigo souza looks like Shrek';
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
});
Working Plunker

Getting no response from $scope in angularjs

This is my method for getting a single user. The console.log prints the right object, but in when i try to access the $scope.user in the HTML I get no response, the tags are empty:
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
});
}
HTML:
<input type="text" name="name" ng-model="user.Username" />
<button ng-click="getByUsername(user.Username)">Button</button>
<h4>{{user.Username}}</h4>
<h4>{{user.Name}}</h4>
<h4>{{user.ImageLink}}</h4>
Edit:
var BlogFeedApp = angular.module('blogFeedApp', ['ngRoute', 'ngResource']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', { controller: MainController, templateUrl: 'posts.html' }).
when('/test', { controller: MainController, templateUrl: 'test.html' }).
when('/new-post', { controller: PostController, templateUrl: 'new-post.html' }).
when('/new-user', { controller: UserController, templateUrl: 'new-user.html' }).
otherwise({ redirectTo: '/' });
}]);
Try removing the return keyword on line 2 of your JS.
Use something like following :
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
return data;
});
}
This should do the trick.
I think it is because your user is not defined when angularjs bootstrap. Can you try define user outside of $http callback?
$scope.user = {};
$scope.user.Username = "";
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
return data;
});
}

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