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
Related
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
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/');
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
I have nested angularJS modules EventList and EventPage.
The directory structure looks like this:
app.js
EventForm
|_ EventList.js
eventListView.html
EventPage
|_EventPage.js
eventPageView.html
Eventlist.js:
angular.module('EventList', ['EventPage'])
.config([ '$routeProvider', function config($routeProvider){
$routeProvider.when(Urls.EVENT_LIST, {
templateUrl: 'app/EventList/event-list.html',
controller: 'EventListCtrl'
});
}])
.controller('EventListCtrl', ['$scope', '$location', '$http', function EventListController($scope, $location, $http) {
}]);
EventPage.js:
angular.module('EventPage', [])
.config([ '$routeProvider', function config($routeProvider){
$routeProvider.when(Urls.EVENT_PAGE + '/:id', {
templateUrl: 'app/EventList/EventPage/event-page.html',
controller: 'EventPageCtrl'
})
}])
.controller('EventPageCtrl', ['$scope', '$routeParams', '$http', function EventPageController($scope, $routeParams, $http) {
}]);
Obviously the templateUrl is hardcoded right now. My question is what is the best way to set the templateUrl in the routeProvider so the modules aren't dependent on the hard coded directory structure and can be taken out and reused in other AngularJS projects without breaking? Is there a way to just get insertViewNameHere.html in the current folder?
If you're using Grunt, this is easy. Not because modularizing AngularJS is trivial, but because all the hard work has already been done for you by the good folk doing angular-bootstrap...
When I faced this problem I simply downloaded their Gruntfile and changed every ui.bootstrap to my-angular-module. Since I mimicked their basic directory structure, it worked right out of the box.
Also, you might want to update the Angular and Bootstrap versions. E.g., change
ngversion: '1.0.8',
bsversion: '2.3.1',
to
ngversion: '1.2.3',
bsversion: '3.0.2',
I've been experimenting a little with Angular.js lately. As part of this I created a very simple set of controllers with an ng-view and templates to trigger depending on the route requested. I'm using angularFireCollection just to grab an array from Firebase. This works fine in the thumbnailController which does not form part of the ng-view.
My problem is that in addition to the data flowing into the thumbnailController, I also need the two other controllers to be able to access the data. I initially simply set the data to either be part of $rootScope or to have the ng-view as a child of the div in which the thumbnailController is set.
However, the issue from that perspective is that each sub-controller presumably attempts to set the data in the template before it is actually available from Firebase.
The solution appears to be using resolve as per the answer to this question angularFire route resolution. However, using the below code (and also referencing angularFireCollection) I get an error message of angularFire being an unknown provider. My understanding is the code below should be sufficient, and I would also add that the usage of angularFireCollection in thumbnailController works fine as I say.
I also experimented with injecting angularFire/aFCollection directly into the controllers using .$inject however a similar issue arose in terms of it being considered an unknown provider.
If possible could someone advise on what the issue may be here?
var galleryModule = angular.module('galleryModule', ['firebase']);
galleryModule.config(['$routeProvider', 'angularFire', function($routeProvider, angularFire){
$routeProvider.
when('/', {
controller: initialController,
templateUrl: 'largeimagetemplate.html',
resolve: {images: angularFire('https://mbg.firebaseio.com/images')}
}).
when('/view/:id', {
controller: mainimageController,
templateUrl: 'largeimagetemplate.html',
resolve: {images: angularFire('https://mbg.firebaseio.com/images')}
}).
otherwise({
redirectTo: '/'
});
}]);
galleryModule.controller('thumbnailController', ['$scope', 'angularFireCollection', function($scope, angularFireCollection){
var url = 'https://mbg.firebaseio.com/images';
$scope.images = angularFireCollection(url);
}]);
function initialController($scope,images){
$scope.largeurl = images[0].largeurl;
}
function mainimageController($scope, images, $routeParams){
$scope.largeurl = images[$routeParams.id].largeurl;
}
I got the chance to dig into this a little bit - it seems like regular services cannot be used in .config sections. I'd instantiate angularFire in the controller instead of using resolve, for example:
galleryModule
.value("url", "https://mbg.firebaseio.com/images")
.controller('thumbnailController', ['$scope', 'angularFireCollection', 'url',
function($scope, angularFireCollection, url) {
$scope.images = angularFireCollection(url);
}])
.controller('initialController', ['$scope', 'angularFire', 'url',
function($scope, angularFire, url) {
angularFire(url, $scope, 'images').then(function() {
$scope.largeurl = $scope.images[0].largeurl;
});
}])
.controller('mainimageController', ['$scope', 'angularFire', '$routeParams', 'url',
function($scope, angularFire, $routeParams, url){
angularFire(url, $scope, 'images').then(function() {
$scope.largeurl = $scope.images[$routeParams.id].largeurl;
});
}]);
This is not ineffecient, since the data is only loaded once from the URL by Firebase, and all subsequent promises will be resolved almost immediately with data already at hand.
I would like to see angularFire work with resolve in the $routeProvider, however. You can use this method as a workaround until we figure out a more elegant solution.