Setting file path and organizing the code in Angularjs - javascript

Hi I have following module, route and controller defined in one file called main.js
var mainApp = angular.module("mainApp", ["ngRoute", "ngResource", "ui"]).
config(function ($routeProvider) {
$routeProvider.
when('/addEmp', { controller: EmpCtrl, templateUrl: 'addEmp.html' }).
when('/addLoc', { controller: LocCtrl, templateUrl: 'newLocation.html' }).
otherwise({ redirectTo: '/' });
});
mainApp.factory("addEmp", ['$resource', function ($resource) {
return $resource('/api/addEmp/:id', { id: '#id' }, { update: { method: 'PUT' } });
}]);
mainApp.factory("addLoc", ['$resource', function ($resource) {
return $resource('/api/newLoc/:id', { id: '#id' }, { update: { method: 'PUT' } });
}]);
//Controllers
var EmpCtrl = function ($scope, $location, addEmp) {
//code here
};
var LocCtrl = function ($scope, $location, newLocation) {
//code here
};
What I am trying to do is organize this one file code into different files. I created script/controller folder where I want to have individual files for controller like
EmpCtrl.js and LocCtrl.js.
When I created the controller files and copied the controller code in it i get error of EmptCtrl and LocCtrl not defined.
Can you please tell me how I can set it up in different folders with appropriate path settings?
Thanks

try this
angular.module("mainApp", ["ngRoute", "ngResource", "ui"]).
config(function ($routeProvider) {
$routeProvider.
when('/addEmp', { controller: 'empCtrl', templateUrl: 'addEmp.html' }).
when('/addLoc', { controller: 'locCtrl', templateUrl: 'newLocation.html' }).
otherwise({ redirectTo: '/' });
});
//in empCtrl.js file
angular.module('mainApp').controller('empCtrl', ['$scope', '$location', 'addEmp',
function ($scope, $location, addEmp) {
//code here
}]);
// same for locCtrl
In your html make sure to include your mainApp.js file before you empCtrl and locCtrl scripts
the key is that you use string names to refer to your controller in your rout configs
{ controller: 'empCtrl' ... }
instead of
{ controller: EmpCtrl ... }
I would recommend that you use require.js to modularize your Angular project, you won't have to worry about order of script includes and it will result in a cleaner project

Related

I had created js (angular js code) file, but this js file not allowing to work other javascript components

I had created js (angular js code) file like below, but this js file not allowing to work other Javascript components.
'use strict';
// declare modules
angular.module('Authentication', []);
angular.module('Home', []);
angular.module('BasicHttpAuthExample', [
'Authentication',
'Home',
'ngRoute',
'ngCookies'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.when('/component1', {
controller: 'ComponentsController',
templateUrl: 'modules/home/views/components/component1.html'
})
.when('/databaseconfig',{
controller: 'DatabaseConfigController',
templateUrl: 'modules/home/view/components/databaseConfig.html'
})
.otherwise({ redirectTo: '/login' });
}])
When ('/component1', { controller: 'ComponentsController', templateUrl: 'modules/home/views/components/component1.html' })
let us say in component1.html file, I am using ng-show/ng-hide is not working. If I use jquery components like hide/show the div based on the radio button is not working. When I am not importing above mentioned js file in component1.html then jquery (hide/show div based on radio button) angularjs (ng-show/ng-hide) components are working.
.run(['$rootScope','$location','$cookieStore','$http',
function ($rootScope, $location, $cookieStore, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
if ($location.path() !== '/login' && !$rootScope.globals.currentUser) {
$location.path('/login');
}
});
}]);

ngRoute dependency injection error but angular-route.js.min is loaded

I can't figure out why the module is failing to load on ngRoute. I have angular and angular-route scripts loading from cdn but I'm still getting the error Error: $injector:modulerr
Module Error
<!--Angular-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-route.min.js"></script>
<script src="app/index.js"></script>
<script src="app/components/blog/blogControllers.js"></script>
// index.js
'use strict';
var pdizzApp = angular.module('pdizzApp', [
'ngRoute',
'blogControllers'
]);
pdizzApp.config(['$routeProvider'], function ($routeProvider) {
$routeProvider
.when('/blog', {
templateUrl: 'blog/view/blog-list.html',
controller: 'BlogListController'
})
.otherwise({
redirectTo: '/blog'
})
});
//blogControllers.js
'use strict';
var blogControllers = angular.module('blogControllers', []);
blogControllers.controller('BlogListController', ['$scope', '$http',
function ($scope, $http) {
$http.get('/api/blog/post').success(function (data) {
$scope.posts = data._embedded.post;
});
$scope.toDate = function(date) {
return new Date(Date.parse(date));
}
}]);
Your config block should look as follows, i.e. the method needs to be declared inside the array that you pass to the config method:
pdizzApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/blog', {
templateUrl: 'blog/view/blog-list.html',
controller: 'BlogListController'
})
.otherwise({
redirectTo: '/blog'
});
}]);

Error: $injector:modulerr Module Error, property 'when' of undefined Angular

I have been researching and trying to figure out this error for 2days now and Still no luck.
To begin I new to angular, and I have following this tutorial : http://jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/
Every was going well until my grid was not filling with data. So I decided to make minor changes to code and now I have ran into this error.
in my js file:
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config([function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
MyApp.factory('Myapp', function ($resource) {
return $resource('/Myapp/:id', { id: '#id' }, { update: {
method: 'PUT' } });
});
MyApp.controller('ListCtrl', ['$scope', 'ds72', function ($scope, Myapp) {
$scope.todos = Myapp.query();
}]);
can some one please explain to me what i am doing wrong?
PS: These are all my Scripts
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-resource.min.js"> </script>
<script src="/Scripts/angular-route.min.js"></script>
try something like that
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
you must add the name of the provider to inject when you use the array declaration
.config(['$routeProvider'/*must be the exact name*/, function(route/*get the $routeProvider value*/) {}])
//equivalent as
.config(function($routeProvider) {})

Angularjs : $locationProvider.hashPrefix("!") ;

I want to show url as "www.test.com/!#" for that i am using $locationProvider.hashPrefix("!") ; but it shows url as "www.test.com/#!" . i want "!" before hash not after hash.
Thanks
var app = angular.module('app', []);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix("!");
$routeProvider.when('/', {
templateUrl: "app.html",
controller: "AppCtrl"
}
)
.when('/Program', {
templateUrl: "detail1.html",
controller: "Redirect"
})
.when('/Program/123456/channel/78458585',
{
templateUrl: "details.html",
controller: "Detail"
});
});
app.controller("AppCtrl", function ($scope) {
});
app.controller("Detail", function ($scope, $location) {
});
app.controller("Redirect", function ($scope, $location) {
$location.path("/Program/123456/channel/78458585")
});
If you want a ! in the URL before the fragment identifier begins, then you need to put it in the URL to start with and not try to do it with Angular.
http://www.example.com/#foo and http://www.example.com/#!foo are different parts of the same page.
But http://www.example.com/#foo and http://www.example.com/!#foo are different pages altogether.

AngularJS - How to use $routeProvider and custom module in config function?

I want to reuse link.
How to use $routeProvider and custom module in config function?
angular.module('urls', []).
factory('$urls', function (
$location
) {
var $urls = {};
$urls.login = function () {
var url = '/login';
return url;
}
return $urls;
});
angular.module('app', ['urls']).
config(function ($routeProvider, $urls) {
$routeProvider.
when($urls.login(), { controller: PageCtrl, templateUrl: 'tem.html' }).
otherwise({ redirectTo: $urls.login() });
});
As I commented you can create a provider instead of a factory and put the URLs in that as the central place:
angular.module('urls', []).
provider('urls', function (){
this.$get = function(){
var obj = {}
obj.login = function(){ return '/login';}
//more urls here, you don't really need function though
return obj;
}
});
angular.module('app', ['urls']).
config(function ($routeProvider, urlsProvider) {
$routeProvider.
when(urlsProvider.login(), { controller: PageCtrl, templateUrl: 'tem.html' }).
otherwise({ redirectTo: urlsProvider.login() });
});
However, you can not inject the $location service to the urls provider. But if you really want to use $location, you can create another service that uses both the urls service and $location service to achieve the same effect like this:
angular.module('urls', []).
service('myUrlService', function (urls, $location){
this.goToLogin = function(){$location.path(urls.login());}//just an example
});
Then you can inject myUrlService to your controllers and do things like this:
myUrlService.goToLogin();

Categories

Resources