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';
});
Related
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>
This is my app.js
var mainApp = angular.module("myapp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/search/login.html'
}).
when('/dashboard', {
templateUrl: 'admin/index.html'
}).
otherwise({
redirectTo: '/'
});
}]);
mainApp.controller('logincntrl',function($scope,$location){
$scope.submit=function(){
var uname=$scope.username;
var upass=$scope.password;
if($scope.username=="admin" && $scope.password=="admin"){
$location.path('/dashboard');
}
};
});`
After clicking on submit.It will redirect to dashboad..That is seperate folder with index.But as i have given view on the first page ..my dashboard contain coming on the first page even with styling..how to make seperate view for dashboard page
You can use <ng-view><ng-view> to have load different
partials. You can have a look into this to have an ideahttp://codepen.io/dhanrajjay/pen/dOjmxL/
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/success', {
templateUrl: 'success.html',
controller: 'sucCtrl'
}).
otherwise({
redirectTo: '/index'
})
}])
app.controller('validateCtrl', function($scope, $http, $location) {
$scope.submit = function(user,password) {
//for local storage validation
$http.get('credentials.json').then(function(response) {
$scope.credentials = response.data;
if((user === $scope.credentials.username) && (password === $scope.credentials.password)){
alert("ok");
$location.path('/success');
}
else{
alert("nit "); }
});
};
})
app.controller('sucCtrl',['$scope', function($scope) {
alert("succs");
}]);
This might be well a beginner question. I am trying to validate my login form and redirect to success.html on success. But I am unable to navigate to next page. I tried using $location.path('/success').
here is the working sample in plunker..
http://plnkr.co/edit/0v7njznHdtwgpaG2NfwA?p=preview
You missed to write ng-view directive to get route changes to displayed on the view. Also you are messed up with the structuring of your page html. Refer below comments that will help you to make it working and improve it.
You should put that ng-view directive in body so that all the view will get loaded on basis of route changes.
Also you should load your form html from the route only, I'd suggest you to add one more route to your config that will say on /login show the form.html(login form)
Config
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/success', {
templateUrl: 'success.html',
controller: 'sucCtrl'
})
.when('/login', {
templateUrl: 'form.html',
controller: 'validateCtrl'
}).
otherwise({
redirectTo: '/login'
})
}])
Markup
<body>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.js"></script>
<script src="login.controller.js"></script>
</body>
Your success.html should be partial, it shouldn't have the script references again to it they have been loaded from the index page only
success.html
<div>
Success Message
</div>
Working Demo
I have problem with below code. When I go to main controller url #/, Angular naturally calls main controller - it execute AJAX request. Problem is, that when I click #/some-url, and then #/ url again, this AJAX request is executed again, which is not desired and unnecessary due to performance. I thought controllers are called only once, but it doesn't look like this is the case, at least with ngRoute.
angular.module('robotsApp', ['ngRoute', 'controllers'])
.config(['$routeProvider', function($routeProvider){
var root = '/static/js/partials/';
$routeProvider.
when('/', {
templateUrl: root + 'main.html',
controller: 'main as main'
}).
when('/some-url', {
templateUrl: root + 'some_template.html',
controller: 'someController'
}).
otherwise({
redirectTo: '/'
});
}]);
angular.module('controllers', [])
.controller('main', ['$http', function($http){
$http.get('/user/recent-gain-loss').success(function(data){
this.recent_gain_loss = data;
}.bind(this));
}]);
<p>{{ main.recent_gain_loss }}</p>
Save the data in to a value and then check if the data are already set.
angular.module('values', [])
.value('recentGainLoss', {})
angular.module('controllers', ['values'])
.controller('main', ['$http', 'recentGainLoss', function($http, recentGainLoss){
if (Object.keys(recentGainLoss).length < 1) {
$http.get('/user/recent-gain-loss').success(function(data){
recentGainLoss = angular.extend(recentGainLoss, data);
});
}
this.recent_gain_loss = recentGainLoss;
}]);
In my angularjs app, I am trying to pass the data from one cshtml view to another view through routing but in details.cshtml, I don't see the data coming into it though I can see the change in URL
Index.cshtml (View1)
{{addprodtocart}}
Controller.js
app.controller('CartController', function ($scope) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
$scope.cid = cartprd[len];
}
});
Details.cshtml ( I don't see the data coming into the span below)
<div ng-controller="CartController">
<span ng-model="cid">{{cid}}</span>
</div>
Myrouting
var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: '/Product/Details',
controller: 'CartController'
});
}]);
I created a plunker for this. I am unable to send the data from page1 to page2
http://plnkr.co/edit/micM7vlslznEIZXP293Y?p=preview
Your problem is your controller is instantiated again while clicking on href and the scope is getting recreated & $scope.cid is set to undefined.
You could achieve the same by using $routeParams which will give the access to what url contains
In your case it would be $routeParams.cid
Code
app.controller('CartController', function ($scope, $routeParams) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
//$scope.cid = cartprd[len];
}
$scope.cid = $routeParams.cid;
});
Update
You should use $routeParams service to get data from url
Code
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: 'page2.html',
controller: 'CartController'
}).when('/', {
templateUrl: 'page1.html',
controller: 'CartController'
});
}
]);
app.controller('CartController', function($scope, $routeParams) {
$scope.myvar = $routeParams.cid; //this will asign value if `$routeParams` has value
console.log($scope.myvar);
$scope.Add = function(c) {
$scope.myvar = c;
}
});
Working Plunkr