I have MVC application, I want make routing for the following URL
http://localhost:2668/Home/User/1
I try
.config(function ($routeProvider, $locationProvider) {
//here we will write code for implement routing
$routeProvider
.when('#/Home/User/:userid', {
templateUrl: '/AngularTemplates/User.html',
controller: 'UserController'
})
.otherwise({ // This is when any route not matched
controller: 'ErrorController'
}) })
And then the UserController as below:
.controller('UserController', ['$scope','$routeParams', function ($scope,$routeParams) {
// $routeParams used for get query string value
//var loc = window.location.href;
//var id = loc.slice(loc.lastIndexOf('/'), loc.length).split('/')[1];
$scope.Message = "This is ORDER Page with query string id value =" + $routeParams.userid;
}])
But I always get "undefined" for the para $routeParams.userid
What is wrong in my code? Please help thanks!
Here is a working example:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
user 11
user 12
<div ng-view></div>
<script>
var app = angular.module('app', ['ngRoute']);
app.config([
'$locationProvider', '$routeProvider',
function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('!');
$routeProvider
.when('/Home/User/:userid', {
template: '<pre>{{ message }}</pre>',
controller: 'UserController'
});
}]);
app.controller('UserController', ['$scope','$routeParams', function ($scope, $routeParams) {
$scope.message = "userid = " + $routeParams.userid;
}]);
</script>
</body>
</html>
JSBin http://output.jsbin.com/geluli
You may read more about default router here (nice examples + tests) https://docs.angularjs.org/api/ngRoute/service/$route
Related
I have found similar question but not getting solution so i have post a question.
I have been implementing and displaying data from database in angular js, below is mu code.
index.php file:
<header>
<script type='text/javascript' src='local-path/js/angular.min.js?ver=4.9.5'></script>
<script type='text/javascript' src='local-path/js/angular-route.min.js?ver=4.9.5'></script>
<script type='text/javascript' src='local-path/js/scripts.js?ver=4.9.5'></script>
</header>
<div ng-controller="mycontrollermenu">
First Name: {{firstname}}
</div>
<div ng-view></div>
<footer></footer>
script.js:
var app = angular.module('wp',['ngRoute',' ']);
app.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl : localized.partials + 'main.php',
controller : 'Main'
})
.when('/:slug', {
templateUrl: localized.partials + 'content.html',
controller: 'Content'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
app.controller('Main',function($scope, $http, $routeParams){
$http.get('wp-json/wp/v2/posts/').success(function(res){
$scope.posts = res;
});
});
app.controller('Content',
['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$http.get('wp-json/wp/v2/posts/?slug=' + $routeParams.slug).success(function(res){
$scope.post = res[0];
});
}
]
);
app.filter('removeHTMLTags', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
});
app.controller('mycontrollermenu',function($scope){
$scope.firstname = "Menu 1";
});
I have added controller mycontrollermenu in to index and js file which is not working, and thow an error like
"Argument 'mycontrollermenu' is not a function, got undefined"
can any one guide me what i have doen wrong in "mycontrollermenu" controller?
Try creating a new .js file like MenuController.js and add the same
app.controller('mycontrollermenu',function($scope){
$scope.firstname = "Menu 1";
});
and in your index.html add <script type='text/javascript' src='MenuController.js'></script>
A couple of questions,
ng-app needs to be there on the root element. Wrap your HTML like <div ng-app="wp">...<div>
localized is a global variable? It is neither injected nor declared.
There is an empty string in the module definition. Forgot to include a dependency?
var app = angular.module('wp',['ngRoute',' ']);
Here I have a fiddle working with your code.
I have a problem with the function $ locationProvider.html5Mode (true), this is the setting:
var app = angular.module("app", [
"ngRoute",
"ngAnimate"
]);
// ROUTE CONFIG
app.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider){
$routeProvider.
when("/archive", {
templateUrl: "archive.php",
controller: "archiveCtrl",
animate: "slide-left"
}).
when("/single", {
templateUrl: "single.php",
controller: "singleCtrl",
animate: "slide-left"
}).
otherwise({
redirectTo: "/archive"
});
$locationProvider.html5Mode(true);
});
In the head tag:
<head>
<base href="/">
</head>
The root of the site is
site.com/main.php
Where main.php contains the div ng-view
Any idea why it does not work?
here is a working example I created on JSFiddle, I removed the templateUrl and use template instead, but it shouldn't matter in this case(you are asking how does html5mode and base work)
html
<div ng-controller="mainCtrl">
single
archive
<div ng-view></div>
</div>
Javascript
var app = angular.module("myApp", [
"ngRoute"
])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/archive", {
template: "<p>archive</p>"
})
.when("/single", {
template: "<p>single</p>"
})
.otherwise({
redirectTo: "/archive"
});
$locationProvider.html5Mode(true);
}])
.controller("mainCtrl", function mainCtrl($scope, $location) {
$scope.$location = $location;
});
JSFiddle
I have following html file
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en-US">
<head>
<script src="{% static 'bower_components/angular/angular.js' %}"></script>
<script src="{% static 'bower_components/angular-route/angular-route.js' %}"></script>
<script src="{% static 'js/hearthstone_guides/controllers.js' %}"></script>
<script src="{% static 'js/hearthstone_guides/app.js' %}"></script>
</head>
<body ng-app="guideApp">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello [[name]]</h1>
<div ng-view></div>
</body>
</html>
The [[ ]] brackets are the new Symbols for angularJS. I will declare them in my angularJS files. The two way data-binding in combination with the name variable (Hello [[name]]) was used for the testing of angular and it works. I can ensure it is included properly.
This is my app.js
var guideApp = angular.module('guideApp', ['ngRoute']);
guideApp
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'GuideDetailController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
.config([
'$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}
])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
and this is my controllers.js
var guideController = angular.module('guideController', []);
guideController.controller('GuideDetailController', [
'$scope',
'$routeParams',
'$http',
function($scope, $routeParams, $http) {
$http.get('http://10.0.3.162:8000/api/guides/' + $routeParams.guideId + '/?format=json')
.success(function(data) {
console.log('success');
$scope.guide = data;
})
.error(function(data, status) {
console.error(status, data);
});
}
]);
When I console.log('foo'); for instance between var guideController = angular.module('guideController', []); and guideController.controller('GuideDetailController', [... it works.
Unfortunately neither does console.log('success'); nor console.log(status, data); work.
Edit:
I changed the controller name now to GuideDetailController as you suggested but it still doesn't work.
This is the error marked in the firefox developer console:
"Error: [ng:areq] Argument 'GuideDetailController' is not a function, got undefined
http://errors.angularjs.org/1.3.20/ng/areq?p0=GuideDetailController&p1=not%20a nanunction%2C%20got%20undefined
minErr/<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:63:12
assertArg#http://10.0.3.162:8000/static/bower_components/angular/angular.js:1590:1
assertArgFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:1600:1
$ControllerProvider/this.$get</<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:8493:9
ngViewFillContentFactory/<.link#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:978:26
invokeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:8281:9
nodeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7791:1
compositeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7140:13
publicLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7019:30
createBoundTranscludeFn/boundTranscludeFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7158:1
controllersBoundTransclude#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7818:18
update#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:936:25
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14889:15
commitRoute/<#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:619:15
processQueue#http://10.0.3.162:8000/static/bower_components/angular/angular.js:13318:27
scheduleProcessQueue/<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:13334:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14570:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14386:15
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14675:13
done#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9725:36
completeRequest#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9915:7
requestLoaded#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9856:1
This is how my guide-detail.html file looks like
<h1>[[guide.title]]</h1>
<h1>{{guide.title}}</h1>
And this is the current results I get when I call this url http://10.0.3.162:8000/#/guide/1
You have put module name as a controller in the route config
Change From:
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'guideController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
To:
config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'GuideDetailController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
First, you should not use the minified versions of the libraries while developing.
Second, your unique route is configured to use the controller 'guideController'. But you have no such controller. The only controller defined is named 'GuideDetailController'.
'guideController' is not a controller. It's a module.
I'm working on an angularjs application that is having an "app.js" file. This file contains the following code:
var app = angular.module("myApp", ['ngRoute', 'ngCookies'])
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$routeProvider
.when('/UserProfileInfo/:UserId', {
templateUrl: 'Views/Users/UserProfileInfo.html',
controller: 'UserProfileInfoController'
})
.otherwise({
redirectTo: "/"
});
}]);
As you can see that above code is having a "UserProfileInfo" route that receives "UserId" route paramenter.
An html page is having a link tag referencing to the "UserProfileInfo" route and the code for this:
<a ng-href="#UserProfileInfo/{{item.UserId}}" ng-hide="hideViewUser" class="glyphicon glyphicon-trash" title="View"></a>
This link is referring to
www.somedomain.com/#/UserProfileInfo/131
The controller code for this UserProfileInfo view is below:
app.controller("UserProfileInfoController", ["$scope", "$location" "$routeParams", "$q", function ($scope, $location, $routeParams, $q) {
$scope.userProfileId = $routeParams.UserId;
}]);
The problem occurrs at this line:
$scope.userProfileId = $routeParams.UserId;
The UserId from $routeParams is coming undefined.
I have used all the required scripts on Index.html page:
<script src="Content/js/jquery-1.11.3.min.js"></script>
<script src="Content/js/bootstrap.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-cookies.min.js"></script>
Kindly help me I'm missing anything.
Please help me in fixing this issue.
Thanks in advance.
For some reason my Angular site isn't working. I've included all the files. but for some reason angular isn't triggered to do something.
This is how my index.html looks like:
<!DOCTYPE html>
<html ng-app="ngTest">
<head>
<title></title>
</head>
<body>
<h2>Test</h2>
<ng-view></ng-view>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="Scripts/angular-animate.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/home/HomeCtrl.js"></script>
</body>
</html>
All included scripts return 200 in the developer console, so I'm sure they are loaded fine.
Then my app.js looks like this:
window.app = angular.module('ngTest', ['ngRoute', 'ngResource', 'ngAnimate']);
app.config(['$routeProvider', '$locationProvider', '$httpProvider', '$provide', function ($routeProvider, $locationProvider, $httpProvider, $provide) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.useXDomain = true;
$locationProvider.html5Mode(true);
$routeProvider
.when('/Home', { templateUrl: '/app/views/home/Home.html', controller: 'HomeCtrl' })
.otherwise({ redirectTo: '/Login' });
}]);
The HomeCtrl.js simply looks lke this:
app.controller('HomeCtrl', ['$scope', function ($scope) {
init();
function init() {
alert('aaa');
}
}]);
And the Home.html only contains a piece of text.
Then when I navigate to: localhost/#Home then I expect it to load my Home.html in the ng-view tag. But that's not happening. It only loads my index.html but no angular code seems to be triggered.
Am I still missing something?
Try:
angular.module('ngTest', ['ngRoute', 'ngResource', 'ngAnimate']).
config(['$routeProvider', '$locationProvider', '$httpProvider', '$provide', function ($routeProvider, $locationProvider, $httpProvider, $provide) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.useXDomain = true;
$locationProvider.html5Mode(true);
$routeProvider.when('/Home', {
templateUrl: '/app/views/home/Home.html',
controller: 'HomeCtrl'
})
.otherwise({
redirectTo: '/Login'
});
}]);
You could do that for controlers :
angular.module('ngTest.controllers', []);//Declare controllers
angular.module('ngTest.controllers').
controller('HomeCtrl',['$scope', function ($scope) {
init();
function init() {
alert('aaa');
}
}]);
By the way, with html5Mode(true) your path will be localhost/Home.