Why use dependency injection in angularjs for controllers? - angularjs

I came across this tutorial.
http://justinvoelkel.me/laravel-angularjs-part-two-login-and-authentication/
The author used dependency injection to inject the login controller in app.js like this.
app.js:
var app = angular.module('blogApp',[
'ngRoute',
//Login
'LoginCtrl'
]);
app.run(function(){
});
//This will handle all of our routing
app.config(function($routeProvider, $locationProvider){
$routeProvider.when('/',{
templateUrl:'js/templates/login.html',
controller:'LoginController'
});
});
The login controller file looks like this.
LoginController.js:
var login = angular.module('LoginCtrl',[]);
login.controller('LoginController',function($scope){
$scope.loginSubmit = function(){
console.dir($scope.loginData);
}
});
I don't understand why the dependency injection is required here.
Here is my version of app.js and LoginController.js which works perfectly fine.
app.js:
var app = angular.module('ilapp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/login', {
controller: 'LoginController'
});
}]);
LoginController.js:
angular.module('ilapp').controller('LoginController', [function () {
this.loginSubmit = function () {
console.dir(this.loginData);
};
}]);
Is there any advantage to the author's approach? What am I missing?

First of all, both are correct way and it should work but you can choose any one method depends upon your project.
Approach 1
In your question, the first approach is modular way. Means, you can register a LoginController controller in a new module LoginCtrl. Here module name LoginCtrl is confusing. you can change the name as loginModule. This approach is helpful for you to organize the files structure for your big application. Also, look this post Angular - Best practice to structure modules
var login = angular.module('loginModule',[]);
login.controller('LoginController',function($scope){
$scope.loginSubmit = function(){
console.dir($scope.loginData);
}
});
var app = angular.module('blogApp',[
'ngRoute',
'loginModule'
]);
app.run(function(){
});
//This will handle all of our routing
app.config(function($routeProvider, $locationProvider){
$routeProvider.when('/',{
templateUrl:'js/templates/login.html',
controller:'LoginController'
});
});
Approach 2
If your application contains minimal pages and no need to split multiple modules, then you can write all your controllers in app.js itself

Related

Angular routing with ng-view is not working

I don't understand why I can't get this to work.
I'll share the relevant code, let me know if you need to see more stuff.
Index.html
<div class="col-md-3">Liberals</div>
app.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when("/liberals", {
templateUrl: "partials/liberals.html"
, controller: "LiberalsController"
});
});
app.controller('LiberalsController', function ($scope, $http) {
var url = "workingURL"; /// changed function to a simple string message to test
$scope.message = "Hello Liberals";
});
(partial view) liberals.html
<h1>Hello</h1>
{{message}}
PS: I'm not working on a political hate website for or against liberals!
As of AngularJS 1.6, the default value of the hashPrefix has been changed to !.
There's two ways to get your routing to work with AngularJS 1.6+:
Add the hashprefix (!) to your href's:
Liberals
Change (remove) the hashPrefix value using $locationProvider:
$locationProvider.hashPrefix('');
I've created a working plunkr in which I used the second approach:
https://plnkr.co/edit/oTB6OMNNe8kF5Drl75Wn?p=preview
The commit regarding this breaking change can be found here

Issue while running browserify on a simple angular app

I'm making this very preliminary attempt of using node/npm/browserify to build my angular app. The ./app/controllers, ./app/directives, ./app/services basically have index.js files which in turn require() the js files! Below is the root js file i.e. public/index.js.
require('./app/controllers/');
require('./app/directives/');
require('./app/services/');
var app = angular.module('myApp', ['ngRoute'])
app.config(function($routeProvider) {
$routeProvider
.when("/movie/:movieId", {
template: require('./views/movie.html'),
controller: 'MovieCtrl as movie'
})
.when("/movie/:movieId/scene/:sceneId", {
template: require('./views/scene.html'),
controller: 'SceneCtrl as scene'
});
});
module.exports = app;
Now after running below command i do get a bundle.js however,
browserify public/index.js -o release/bundle.js
However, the below line in bundle.js throws the error "Uncaught ReferenceError: app is not defined"
app.controller('MainCtrl', function ($route, $routeParams, $location, MyFactory) {
Now, i was assuming because var app is specified in index.js it should be accessible in MainCtrl.js. Could someone suggest how i could make this work?
----- Adding some more info ------
app/controllers/index.js contains below code:-
require('./MainCtrl.js')
require('./MovieCtrl.js')
require('./SceneCtrl.js')
And MainCtrl.js contains below code:-
app.controller('MainCtrl', function ($route, $routeParams, $location, MyFactory) {
//...
})
I don't know where the line in your code is... it isn't clear from the question, but anyway:
Now, i was assuming because var app is specified in index.js it should be accessible in MainCtrl.js.
That assumption is false. You will need to pass in a reference to whatever you need when you instantiate whatever you included.
For example..
var mainCtrl = new MainCtrl(app);
Ok, so i kind of understood what was going on. var app is local and cannot be accessible anywhere else. Once i set app to the global scope (which is obviously a horrible thing!) and required files after declaring app, it worked. This is mostly not the correct way of doing it, but as i mentioned this was a very preliminary attempt.
app = angular.module('myApp', ['ngRoute'])
app.config(function($routeProvider) {
$routeProvider
.when("/movie/:movieId", {
template: require('./views/movie.html'),
controller: 'MovieCtrl as movie'
})
.when("/movie/:movieId/scene/:sceneId", {
template: require('./views/scene.html'),
controller: 'SceneCtrl as scene'
});
});
require('./app/controllers/');
require('./app/directives/');
require('./app/services/');

Angularjs, global Service throwing error

Stuck in a situation, my app is configured in a way, that I have an app controller, which is using ng-route to route between different views and partials, Now from the login controller, I am making a request to get some data, now I want that data to be accessed globally in the application. Now when I create a service, I am injecting it in the app controller module, but I am getting an error service is not defined,
My app.js:
var myApp = angular.module('app', ['loginMod', 'dashboardMod', 'newRequestMod', 'ngAnimate', 'ui.bootstrap', 'ngRoute', 'userDetailService']);
myApp .config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'resources/pages/login.html',
controller:'loginController'
})
...
Now in my logincontroller i am using the service :
userDetailShareService.sendData(loginModel);
console.log("Checking the service if it works " + userDetailShareService.getData);
userDetailShareService.js:
var app = angular.module('userDetailService',[]);
app.factory('userDetailShareService', function($timeout,$rootScope) {
var service = {};
var dataArray = [];
service.data = [];
service.sendData = function(data){
//dataArray.push(data);
dataArray=this.data;
};
service.getData = function(){
return dataArray;
};
return service;
});
No I am not sure what is throwing that error, the app.js is the first page that is hit, and the data mentioned in login controller is some response data, that I am getting in login controller and then I want to share across my entire application, every controller the data that I get, I do not want to use $rootScope as it will burden the same.
Could anybody please reply, I am in a great need. Thanks in advance.

Angular JS problems with Ng-Route, Gulp, and Json

I'm pretty new to the world of front end development and I'm working through my first project with AngularJS. I'm also using Yeoman, Gulp, Bower to set up my project, which is also bran new to me... I've kind of crafted a build from the yo generator Gulp Angular and put my own personal touches to it. I'm sure I did more harm than good :p but I'm learning.
Anyways I've been coding all day and am really stumped why my project is having trouble when I use the ng-route. The home display works correctly but when I try to click on a link to a deeper page it just refreshes back to the home. I'm using Json files rather than a server and the Gulp Angular set up has all my files compiled to another folder when launching a server. Is there any chance the issue could lie within the compiler?
I'm starting to go crazy so I think I'm gonna call it quits for the night but if anyone has the time and the generosity to look over my github repo I would be over joyed :)
Thanks
https://github.com/jleibham/BhamDesigns.git
App Module
(function() {
'use strict';
var bhamDesignsApp = angular.module('bhamDesignsApp', ['ngAnimate', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngRoute', 'mm.foundation', 'appControllers']);
bhamDesignsApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/projects', {
templateUrl: 'partials/projects.html',
controller: 'ProjectsController'
}).
when('/projects/:projectId', {
templateUrl: 'partials/gallery.html',
controller: 'GalleryController'
}).
otherwise({
redirectTo: '/projects'
});
}]);
})();
App Controller
(function() {
'use strict';
var appControllers = angular.module('appControllers', []);
appControllers.controller('ProjectsController', ['$scope', '$http',
function ($scope, $http) {
$http.get('app/json/projects.json').success(function(data){
$scope.projects = data;
});
$scope.orderProp = '-year';
}]);
appControllers.controller('GalleryController', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.projectId = $routeParams.projectId;
}]);
})();
You are calling the wrong url and your routes do not recognize the url you do call with your href, so it redirects you. In you are going to call this:
href="#/json/galleries/(what ever the project.id is)
Then your routing should look similar to this:
when('/json/galleries/:projectId', { /// the rest of your code
You are going to want to use $routeParameters with ngRoute. here is a great example

Create $ angular service to inject in other components

I am using Angular and I need to define routing in ng-route config but also in my services to be used by $http in services methods.
The problem is that the route strings change in my application according to language ... For example for an about us page I might have:
"en/about-us", "pt/quem-somos", "fr/ ..."
The application has a RouteProvider that returns route strings by key.
The idea would be to create a script on the fly for a service that injected in angular components would allow to get those routes strings.
<script type="text/javascript">
// Create $routes service using backend code ...
</script>
This would be used on app.config as follows:
app.config(['$routeProvider', function($routeProvider, $routes) {
$routeProvider.
when($routes.getByKey('about.home', {
templateUrl: 'about/home.html',
controller: 'AboutController'
})
}
But also in a service as follows:
application.service('CountryService', function ($http, $routes) {
return {
GetList: function () {
return $http.get($routes.getByKey('api.countries.list');
}
}
});
My problem is how to write the JS part of such a service and to plug it into angular components. Is it possible to create such a service?
I would not conflate view routes from the API endpoints - these are different creatures.
And you don't need to create a route per language - just use language as a parameter:
$routeProvider
.when("/:lang/about-us", {
template: "<h3>About Us</h3> in lang: {{language}}",
controller: function($scope, $routeParams, $location){
$scope.language = $routeParams.lang;
}
})
.when("/:lang/something-else", {
template: "<h3>Something Else</h3> in lang: {{language}}",
controller: function($scope, $routeParams){
$scope.language = $routeParams.lang;
}
})
plunker

Resources