module dependency with ngRoute breaks angular rendering - javascript

I am trying to use Mean stack in my website project. I am using ngRoute for routing and I want to add bootstrap carousel to my main page. I am trying to put angular team carousel component from this page.
While I am trying to implement this, I realize as soon as I try to add module dependency ( which is var app = angular.module('myApp', []) ) to my controller , angular breaks (without any error) and nothing appear in page. If I delete, everything is working normal. I assume this is related with routing ?
Project Structure;
-myApp
-node_modules
package.json
server.js
-public
-controllers
-lib
-views
app.js
index.html
app.js ;
(function(){
var app = angular.module('filmSevmem', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({redirectTo:'/main'});
});
})();
MainController.js;
(function(){
var app = angular.module('myApp');
var MainController = function ($scope, $http) {
....... // codes from carousel
.......
app.controller('MainController', MainController);
})();
If I add , [] or ['ngAnimate', 'ui.bootstrap'] or anything to right of 'myApp', nothing work and I get empty page from my localhost. What can cause this problem ? What should I do ? Thank you.

var app = angular.module('myApp'); means get me the module myApp.var app = angular.module('myApp', [listOfDependencies]); means create the module myApp with all of the listed dependencies. So if you put square brackets in app.js AND in mainController.js, then you overwrite the previously created. The simplest solution would be to add ngAnimate and ui.bootstrap in your app.js like this: var app = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap']);
If you don't want to have all your dependencies in your root module, you can make submodules like var controllers = angular.module('myApp.controllers', ['ngAnimate']), and include this in your app.js like var app = angular.module('myApp', ['myApp.controllers']);

Why you are creating two different modules? And even you are not injecting the first module while creating the second.
By no chance your application is gonna work until and unless you code everything using single module or inject one module in another!

Related

Laravel mix and AngularJs

I'm trying to use Laravel Mix, which runs webpack, to compile an angular app into one file. I get the error:
Uncaught ReferenceError: app is not defined
my webpack.mix.js:
const { mix } = require('laravel-mix');
mix.js('resources/assets/js/dependencies.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
my bundle.js :
//load angular
require('angular');
//Load Angular's plugins
require('angular-ui-router');
//Init Angular app
require('./app/app');
//Load angular controllers
require('./app/Controller/aboutController');
....
//Load angular directive
require('./app/Directive/directive');
//Load angular services
require('./app/Services/AccountService');
....
My app/app.js:
var app = angular.module('app', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'app/View/homeView.html',
controller: 'homeController'
})
...
}]);
app.run(['$state', '$rootScope', function ($state, $rootScope) {
//APP RUN
}]);
I get the Uncaught ReferenceError: app is not defined when I call app.controller(), for example app/Controller/aboutController.js:
app.controller("aboutController", ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {....}
Am i missing something? If i load all the file one by one using html it works fine.
If you are defining your app's controller in separate file , then you cannot use directly app as there is no reference . You first have to refer to the module .
angular.module('app')
.controller('aboutController'....
Let me know if this work for you.
For anyone looking to do this in a more automated way for their next Laravel project, I created an article to explain how. Tested on Angular versions 4-7 with Laravel versions 5.4-5.8. I hope it helps!

How to refactor angular dependency injection for concatination and minification?

I have written my angular application into seperate files for my readability and ways to easily find things to edit/code. This is my app.js that requires the dependencies.
app.js
var app = angular.module('app', ['ngResource', 'ngRoute', 'app.services', 'app.controllers', 'app.feed','app.directives', 'app.factories']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
...
}]);
This is an example of how the dependencies are written out.
services.js
var app = angular.module('app.services', []);
app.factory('AuthService', ['$scope'], function($scope) {
...
}]);
However, when I try to concat the scripts, app is redefined constantly. I thought of taking out the var declaration but, I like to keep the files separate.
How would I be able to write this out where the dependency injections stay intact for my app.js, while still keeping the files separate.
To prevent the constant re declaration of you app variable, you can take advantage of the module pattern: Angular Style Guide:Modules.
Instead of explicitly declaring app in every dependency:
var app = angular.module('app.services', []);
app.factory('AuthService', ['$scope'], function($scope) {
...
}]);
You can define you service, component, directive, controller, etc as a part of the correct module:
angular.module('app.services')
.factory('AuthService', ['$scope'], function($scope) {
...
}]);
Declaring an 'app.services' module would only need to happen once.
See : Angular Style Guide:Modules for better explanations.

$routeParams not populating

Some I'm new to routing and single page web apps, but I've been trying to learn Angular correctly. There's some trouble I'm experiencing with it however and a few weird questions. I followed a guide on structuring your directory and mine looks something like this:
app/
components/
profile/
profile.html
ProfileModel.js
ProfileController.js
ProfileFactory.js
app.module.js
app.routes.js
My main module is located in app.module.js and is dependency injected with ngRoute and profile.app (the module for profile view from ProfileModel.js). It is declared like this:
angular
.module('app', ['ngRoute', 'profile.app'])
.controller('MainController', MainController);
function MainController() {
this.message = 'This is the home page';
}
Then in my app.routes.js file, I have declared all the routes the applications needs (so far only one, which is profile):
angular
.module('app')
.config(routeConfig);
routeConfig.$inject = ['$locationProvider', '$routeProvider'];
function routeConfig ($locationProvider, $routeProvider) {
$routeProvider
.when('/user/:user_id', {
templateUrl: '/app/components/profile/profile.html',
controller: 'ProfileController',
controllerAs: 'profile'
}
)
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
This is my ProfileController.js:
angular
.module('app.profile')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['ProfileFactory', '$routeParams'];
function ProfileController(ProfileFactory, $routeParams) {
var vm = this;
vm.user_id = $routeParams.user;
console.log($routeParams.user_id);
vm = ProfileFactory.userProfile(vm.user_id); //Gets the profile of the user and sets to to vm
}
So I have two main questions. $routeParams.user_id is logged as nothing despite I have defined the route in app.routes.js. This is weird because I have an ng-view directive in my index.html (the HTML file that includes every single .js file). Which means that I should have immediate access to the routing parameters once the controller and its dependencies are instantiated. However, when I go to http://example.com/user/1, I get nothing logged (undefined).
My second question is I included ngRoute as a dependency in profile.app and my main module (in which profile.app is a dependency). However, I later removed ngRoute from profile.app as a dependency, yet I left the injection of $routeParams inside my ProfileController and AngularJS didn't complain at all. This seems weird because the dependency is no longer explicitly present inside profile.app. So how come I can still seemingly inject $routeParams despite not having ngRoute in my profile.app module? Is it because it is getting ngRoute from the main module?
I believe the problem is that you are setting controllerAs to 'profile' but then in the controller you write var vm = this;
These two need to be the same so you could write controllerAs: 'vm', or var profile = this;

Uncaught Error: [$injector:modulerr with angualrJs when i use routing

this is part of my problem = https://jsfiddle.net/2vrz38d6/
it contain just the js part open the console to see what i have
i get confused to solve this error
Error: $injector:modulerr
Module Error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.10/$injector/modulerr?p0=myApp&p1=Error%3A%…3A9641%2Fassets%2Fglobal%2Fplugins%2Fangularjs%2Fangular.min.js%3A38%3A435)
My Error happen with routing in angularJs
the error which i took it is :
my Error page here
my code is :
(function () {
var MyApp = angular.module('myApp');
MyApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/expenses.html',
controller: 'CurriculumController'
})
.otherwise({
redirectTo: '/'
});
and the controller
MyApp.controller('CurriculumController', ['$scope', '$rest', function ($scope, $rest) {
//some stuf here
for my script angular file :
in the first i have this
<script src="/assets/global/plugins/angularjs/angular.min.js"></script>
and in the middle of the project i have
the file of my angular apps
<script src="/Scripts/NGModel/Curriculum/Curriculum.js"></script>
and after that the file of the routing part for angularjs
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
As people above have suggested, you need to include that file, but you also need to make sure that you are doing it in the correct order as well in your index file. I suppose trying a different set of CDNs wouldn't hurt either.
<script src="https://code.angularjs.org/1.3.15/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-route.min.js"></script>
Also, in your route configurations, just a mention that you can do this as well for your otherwise:
MyApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/expenses.html',
controller: 'CurriculumController'
})
.otherwise("/");
});
you have to include angular-route.js.
Dependency injection would be angular.module('myApp', ['ngRoute']);
EDIT as the inclusion of Angular libraries were updated in the OP's problem statement :-
Replace
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script> with
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular-route.min.js"></script> as you have mentioned in comments that you are using v1.3.10
And as #Garrett has suggested, add,
.otherwise("/");
You will need to make this work:
1) Add the angular-route file:
Include the file below the angular.js
<script src="angular-route.js">
2) Inject the ng-route at the definition of your app:
angular.module('myApp', ['ng-route']);
you should add your dependencies in to the module like this
var app = angular.module('myApp', ['ngRoute']);

Angular module needs to be defined twice

I have been playing around with some angular code and I found that it has app.controllers twice on the page. Once in the module of app towards the top and once at the bottom. But when I remove one or the other the code breaks. I don't know why you need both since the app.services doesn't need that or the directives or filters. Any insights on why?
(function () {
angular
.module('app',
[
'app.controllers',
'app.services',
'app.directives',
'app.filters'
]
)
.config(['$sceDelegateProvider','$routeProvider',
function ($sceDelegateProvider, $routeProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://maps.google.com/**']);
$routeProvider
// Home
.when('/',
{
templateUrl: 'partials/home.html'
}
)
// Default
.otherwise('/');
}
]
);
angular.module('app.controllers', []);
}());
This code :
.module('app', [
'app.controllers',
'app.services',
'app.directives',
'app.filters'
]);
is creating a new module named app. Inside [] you will find the list of dependencies modules. app.controllers is one of your app dependencie.
Whereas this code :
angular.module('app.controllers', []);
is creating a new module called app.controllers with no dependencies => [] (empty array).
To summarize
To create a new module
angular.module('MODULE_NAME', []); (Note there are [])
To access the module previously created
angular.module('MODULE_NAME');
Convention name xx.yy (like app.controllers) helps to know that the module xx.yy depends of xx (app.controllers is a dependency of app)

Categories

Resources