ng-route doesn't work with other modules - javascript

I have the following code
var balaitus = angular.module("balaitus", ["ngRoute"]);
// configure our routes
balaitus.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
})
.when('/home_usuario', {
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
})
// route for the about page
.when('/estadisticas', {
templateUrl : 'estadisticas.html',
controller : 'estadisticasCtrl'
})
// route for the contact page
.when('/hashtags', {
templateUrl : 'hashtags.html',
controller : 'hashtagsCtrl'
})
.otherwise({
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
});
});
// create the controller and inject Angular's $scope
balaitus.controller('usuarioCtrl', function($scope) {
// create a message to display in our view
$scope.message = 'Hi! This is the home page.';
});
balaitus.controller('estadisticasCtrl', function($scope) {
$scope.message = 'Hi! This is the estadisticas page.';
});
balaitus.controller('hashtagsCtrl', function($scope) {
$scope.message = 'Would you like to contact us?';
});
The code simply routes different pages, and set the corresponding controller. It works fine, but when I add another angular module between [ ], for example ngFileUpload or ui.bootstrap.demo, ng-route doesn't work, ¿but why?

you should add it in the constructor, like:
var balaitus=angular.module("balaitus", ['webix', 'ngRoute','ui.router']);
balaitus.config(['$stateProvider', '$urlRouterProvider', '$routeProvider', '$locationProvider', '$qProvider', function ($stateProvider, $urlRouterProvider, $routeProvider, $locationProvider, $qProvider) {
$routeProvider ....
and of course include the js files in ur html code
<script src="Scripts/angular-route.js"></script>

Related

Include Javascript file in Angular [duplicate]

This question already has an answer here:
how can i load javascript file along with ng-include template
(1 answer)
Closed 3 years ago.
I have an Angular app which redirects route to a particular html page. But how to include related javascript with this.
For example if i click red it will load red.html. but i need to load red.js also additionally.
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.when("/red", {
templateUrl : "red.html";
})
.when("/green", {
templateUrl : "green.html"
})
.when("/blue", {
templateUrl : "blue.html"
});
});
</script>
You should use controller property:
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
controller : "MainController"
templateUrl : "main.html"
})
.when("/red", {
controller : "RedController";
templateUrl : "red.html";
})
.when("/green", {
controller : "GreenController"
templateUrl : "green.html"
})
.when("/blue", {
controller : "BlueController"
templateUrl : "blue.html"
});
});
</script>
<script src="controllers.js"></script> // add controllers files
controllers.js
angular
.module('myApp')
.controller('MainController', function() {
//your MainController code
});
angular
.module('myApp')
.controller('RedController', function() {
//your RedController code
});
angular
.module('myApp')
.controller('GreenController', function() {
//your GreenController code
});
angular
.module('myApp')
.controller('BlueController', function() {
//your BlueController code
});

Routing is not working in AngularJS app

I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});

Resolve function not being injected in controller [Angular JS]

angular
.module('madkoffeeFrontendApp', [])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/articles.html',
controller: 'MainCtrl',
resolve: {
articles: function(articleService,$q) {
// return articleService.getArticles();
return 'boo';
}
}
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
My above code contains the resolve.
angular.module('madkoffeeFrontendApp')
.controller('MainCtrl', ['$scope',
function($scope, articles) {
console.log(articles);
}]);
When I tried to inject articles in the array as shown below, it gives an error but as far as I know that's the correct way to inject a resolve function:
angular.module('madkoffeeFrontendApp')
.controller('MainCtrl', ['$scope','articles',
function($scope, articles) {
console.log(articles);
}]);
My articles resolve function is not being injected. I tried returning just a string (example: 'boo') as shown to test if articles dependency works or not, and it doesn't i.e. it returns undefined. What could be the reason?
Here's a Plunker to demonstrate the resolve message. As you'll see in the example, it's the same structure as the code you posted and should work fine.
Click the about page to see the resolve message.
http://plnkr.co/edit/FomhxYIra5GI7nm1KpGb?p=preview
Code:
var resolveTestApp = angular.module('resolveTestApp', ['ngRoute']);
resolveTestApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController',
resolve: {
resolveMessage: function() {
return 'This is the resolve message';
}
}
})
});
resolveTestApp.controller('mainController', function($scope) {
$scope.message = 'Everyone come and see how good I look!';
});
resolveTestApp.controller('aboutController', ['$scope', 'resolveMessage', function($scope, resolveMessage) {
$scope.message = resolveMessage;
}]
);
It may be the version of Angular you're using or a problem when you're minifying your code.

Removing # from angularjs and making url pretty

I want to remove the # from the url
I have used the locationProvider and had in the index.html
Locationprovider is given as
scotchApp.config(function($routeProvider, $locationProvider) {
..
$locationProvider.html5Mode(true);
Here is my script.js
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
$locationProvider.html5Mode(true);
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
This is the follow up of this question. I still didn't get the solution. I would accept both answer if it was answered.
Here is the plunkr of the example which i wanted to do.
Note :
This is my project folder
localhost/test/angular
So, i have this link in the about
localhost/test/angular/about
Request : Pls download the source from plunkr and have a try over it.
I am not getting any error but nothing appears in the body sections
Thanks
To link around your application using relative links, you will need to set this html code in the head of your document.
<base href="/your-base-if-needed">
or
<base href="/">
but the HTML5 mode set to true should automatically resolve relative links

$scope does not return any value

I am trying to access $scope variable inside my controller . when I console my $scope it shows number of values but when I try to access it via $scope. it return undefined.
I have attached screen shot of $scope
Here you can see it have $id, $parent , templateUrl but when i am trying to access it via $scope.id , $scope.parent , $scope.templateUrl it return undefined .
Edited :
I am trying to access template url . actually I want to attach some params with template url so that I can get them in my backend function
here is my code :
brainframeApp.config(
['$interpolateProvider', '$locationProvider', '$httpProvider', '$routeProvider',
function($interpolateProvider, $locationProvider, $httpProvider,
$routeProvider) {
//configuring angularjs symbos to not to conflict with Django template symbols
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
//$locationProvider.html5Mode(true).hashPrefix('!');
// setup CSRF support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
console.log("TestDavy: App");
//The route provider
$routeProvider.
when('/', {
templateUrl: '/static/engine/partials/listbrainframes.html',
controller: 'brainframeCtrl'
}).
when('/brainframe/', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
when('/brainframe/:id', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
otherwise({
redirectTo: '/'
});
}]);
my controller :
brainframeAppControllers.controller('brainframeCtrlx',
['$scope', '$routeParams', function($scope, $routeParams) {
//console.log($scope.parent);
//$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope);
$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope.templateUrl);
}]);
When I put console.log on $scope, am able to see only these properties:
["$$childTail", "$$childHead", "$$nextSibling", "$$watchers", "$$listeners", "$$listenerCount", "$id", "$$ChildScope", "$parent", "$$prevSibling"]
If you want to access the template URL inside your controller:
brainframeApp.run(function($rootScope) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
$rootScope.templateUrl = next.$$route.templateUrl;
});
});
Now inside your controller, inject $rootScope and get the template URL
$rootScope.templateUrl

Categories

Resources