I am fairly new to Angular, and I am trying to do an example with a parameter. The one without the parameter works fine, but the link with the parameter does not work. What am I doing wrong here?
The app and controller:
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$routeProvider','$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$routeProvider
.when('/NewOrder', {
templateUrl: 'templates/NewOrder',
controller: 'AddOrderController'
}).when('/ShowOrders/:orderID', {
templateUrl: function (params) {return '/templates/ShowOrders?orderID=' + params.orderID; },
controller: 'ShowOrdersController'
}).otherwise({
redirectTo: '/ShowOrders'
});
}
]);
myApp.controller('AddOrderController', function ($scope) {
$scope.message = 'This is the add new order controller screen';
});
myApp.controller('ShowOrdersController', function ($scope,$routeParams) {
$scope.message = 'This is the show orders controller';
$scope.order_id = $routeParams.orderID;
});
The Route.config file:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "NewOrder",
url: "templates/NewOrder",
defaults: new { controller = "Templates", action = "AddOrder" });
routes.MapRoute(
name: "ShowOrders",
url: "templates/ShowOrders/{orderID}",
defaults: new { controller = "Templates", action = "ShowOrders", orderID = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Defaults",
url: "{*url}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The html file:
<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-strict-di>
<head>
<title>AngularJS Routing example</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
<li> Add New Order </li>
<li> Show Order </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
#*<script src="app.js"></script>*#
<script src="~/Scripts/myApp.js"></script>
</body>
First thing you shouldn't be confuse between angular-router & ui-router, as currently you are using angular-route, thus you should use ngRoute module instead of ui-router
var myApp = angular.module('myApp', ['ngRoute'/*, otherDependencies */]);
You can not have params inside your templateUrl function while using 1.0.7 version of angular, instead you should have used latest version which have added support that you could have $routeParmas in your $routerProvider templateUrl function (Actually angular added this support since 1.1+).
Or if you wanted to stick with the older version for some reason then you could include the $routeParams as dependency in your .config function.
.when('/ShowOrders/:orderID', {
templateUrl: '/templates/ShowOrders?orderID=' + $routeParams.orderID,
controller: 'ShowOrdersController'
})
EDIT note - based on Charlietfl's comment below, this is the wrong answer. Per Stack overflow's preference I won't delete it, because having the wrong content can sometimes help guide users to an answer as well.
You'll have to excuse be because it's been a little over a year since doing angular + MVC4 ... I'm not even sure this deserves to be an "answer" over a comment
BUT
My recollection of angular routes is such that they only happen based on the things that happen AFTER the hash (barring a configuration setting)
Could you take a moment to test the route:
/ShowOrders/123#/ShowOrders/123
and see if anything changes? meantime I'll did through some old code to see if I can recall the nit-pickle-y bits of angular routing.
Related
I am making a web app using Angular for front-end.
If user whose role is teacher trying to access applicant's portal, I want to block them by showing 404.html template. I do not want to redirect the users to www.example.com/404 but rather just let them stay at where they are at www.example.com/teacher but render 404.html template.
I am not sure how I can achieve this using ngroute. Here is the code what I have in app.js:
app.config(['$routeProvider', '$locationProvider', 'CookieProvider',
function ($routeProvider, $locationProvider, CookieProvider) {
var cookieData = CookieProvider.$get().getCookieData();
$routeProvider.when('/applicant', {
templateUrl: '/front-end/public/views/Prescreening/review.html',
controller: 'ReviewCtrl',
resolve:{
"check":function($location, CookieService) {
var cookieData = CookieService.get();
if(cookieData["user_role"] == 'teacher'){
$location.path('/404')
}
}
}
}).when('/404', {
templateUrl: '/404.html'
}).otherwise({
templateUrl: '/404.html'
});
}]);
How can I render 404.thml without redirecting the user to /404 ?
Let's say you have a state like this.
.state('dashboard.users', {
url: '/users/:isAdmin',
templateUrl: 'modules/dashboard/templates/users.html',
controller: 'usersController',
})
Try this.
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run(function($rootScope, $location) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
// You can pass the user role to the params
// of the state and you will see that on the
// toParams call callback ex. {isAdmin:false}
if(!toParams.isAmin){
toState.templateUrl = "modules/404/templates/404.html";
}
});
})
})
UPDATE
The callback toState actually contains the following
url = url of the current state ex. /user
templateUrl = path to the template ex. path/to/something.html
controller = the controller name of the state ex. usersController
name = the state name ex. dashboard.user
When this line gets executed toState.templateUrl = "modules/404/templates/404.html"; The current template of your state which falls under the <div ui-view></div> will have the 404.html that you desire.
IMPORTANT
You must use ui.router and not ngRouter to make this implementation work.
After some efforts I got it working... Here are the different codes...
I have used bower so please replace with your paths..
Here is the plunk.. I got it working..
https://plnkr.co/edit/dK7n6PmhldJ1p0plWPp2?p=preview
index.js
var app = angular.module('myApp',['ngRoute']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/applicant', {
template: 'Applicant!',
controller: function($scope){
alert("Applicant Controller");
}
})
.when('/404', {
templateUrl: '404'
})
.otherwise({
templateUrl : '404.html'
});
}]);
index.html
<html>
<head>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src = "index.js"></script>
</head>
<body ng-app="myApp">
<ng-view></ng-view>
</body>
</html>
404.html
<h1>404 page</h1>
I have an AngularJS application. I recently added couple of routes but they don't work. The rest is working fine.
I included them in my index.html
<script src="privacy_policy/privacy_policy.js"></script>
<script src="contacts/contacts.js"></script>
I added them in my app.js file:
angular.module('myApp', [
...
'myApp.privacy_policy',
'myApp.contacts',
...
]).
The route system:
$routeProvider.when('/privacy_policy', {
templateurl: 'privacy_policy/privacy_policy.html',
data: {
needauth: false
}
});
$routeProvider.when('/contacts', {
templateurl: 'contacts/contacts.html',
data: {
needauth: false
}
});
I added a simple controller:
'use strict';
angular.module(
'myApp.privacy_policy', ['ngRoute']
).
config(['$routeProvider', function($routeProvider) {
}]).
controller('PrivacyPolicyCtrl', ["$scope", "$http", "store", "URL", function($scope, $http, store, URL) {
}]);
And some simple html:
<div ng-controller="PrivacyPolicyCtrl" class='row below-header'>
PRIVACY POLICY
</div>
Finally I created a simple link to that view:
<li><a href='/privacy_policy'>Privacy policy</a></li>
I created the SAME things for contacts but if I click on those link ng-view is completely empty.
All the others route are working fine and I can't see any difference. I get no error on the console.
In the route system in app.js If I put a different template, for example:
$routeProvider.when('/privacy_policy', {
templateurl: 'faq/faq.html',
data: {
needauth: false
}
});
The faq page is diplayed correctly. What am I missing?
Ok I finally find you what the problem is.
I only needed to change this:
templateurl: 'contacts/contacts.html',
with this:
templateUrl: 'contacts/contacts.html',
I am trying to set up my ui-routes and it seems simple but I don't know what's wrong. I have the following example, making a simple web template with angular ui-router
<script src="./bower_components/angular/angular.min.js" >></script>
<script src="./bower_components/angular-bootstrap/ui-bootstrap.min.js" >></script>
<script src="./bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="./app/app.module.js"></script>
<script src="./app/app.route.js"></script>
I've written the app.module.js ,app.route.js and index.html something like this
app.module.js
'use strict';
angular.module('ezer',[ 'ui.router'
])
.controller('main-cntrl',['$scope','$rootScope','$state',function($scope,$rootScope,$state)
{
$scope.message = "abc";
}]);
app.route.js
angular.module('ezer')
.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root',{
url: '',
views: {
'header': {
template: '<h1>My header</h1>',
controller: 'main-cntrl'
},
'footer':{
template : '<h1>My footer</h1>',
controller: 'main-cntrl'
}
}
})
}]);
index.html
<body ng-app="ezer" ng-controller="main-cntrl">
<div ui-view="header"></div>
<div ui-view="footer"></div>
</body>
In my console there are no errors at all.. I don't understand, what is the matter?
In your routes where you have the url, I think you should have 'url' : '/'.
in your app.route, the url should at least be '/' and not ''
I am using UI-Router and my html looks something below:
<body ng-controller="myCtrl">
<h1>Hello Plunker!</h1>
<ul>
<li ng-repeat = "guy in guys">
<a ui-sref="person">{{guy}}{{$index+1}}</a>
</li>
</ul>
</body>
The output is below:
Hello Plunker!
File1
File2
File3
and my angular code is something like below:
var app = angular.module('app', ['ui.router']);
app.controller('myCtrl', function($scope) {
$scope.val = "This is my Message..."
$scope.guys = ['File1','File2','File3']
});
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('person{something needs to be here}', {
url: "/route1",
templateUrl: "file1.html"
})
.state('person{something needs to be here}', {
url: "/route2",
templateUrl: "file2.html"
})
})
Can someone help with with what needs to be populated here, My goal is that clicking File1 should open file.html and clicking file2 should open file2.html
In short my question is how do I open different files/templates/partials when clicking on items that are repeated in an ng-repeat directive and how to specify url parameters in state of UI-Router
thanks much
http://plnkr.co/edit/p6Qlzh7XjjeXUJ5I8Z8h?p=preview
I created an updated plunker here
State would be looking like this:
.state('guy_route2', {
url: "/route/{index:int}",
templateProvider: function($templateRequest, $stateParams) {
var index = $stateParams.index + 1;
var templateName = 'file' + index + '.html';
return $templateRequest(templateName);
},
})
this would be the body:
<body ng-controller="myCtrl">
<ul>
<li ng-repeat = "guy in guys">
<a ui-sref="guy_route2({index: $index})">{{guy}}</a>
</li>
</ul>
<h3>Target for state</h3>
<div ui-view=""></div>
</body>
See the <div ui-view=""></div>, essential target for our states. And the ui-sref:
ui-sref="guy_route2({index: $index})"
where we pass the state name 'guy_route2', and the function call contains object representing the state params ({index: $index})
Check that all here
The templateProvider "magic" details could be found here:
Angular pass paramters in templateurl in stateprovider
Trying to Dynamically set a templateUrl in controller based on constant
EXTEND:
With a radio I would adjust it like this
<h3>radio</h3>
<ul>
<li ng-repeat="guy in guys">
<input type="radio"
value="{{$index}}"
ng-model="Model.selected"
ng-change="go(Model.selected)"
id="something{{$index}}"
/><label for="something{{$index}}">{{guy}}</label>
</li>
</ul>
And the go function
$scope.Model = { selected: null };
$scope.go = function(index){
$state.go('guy_route2', {index: index}) ;}
});
Check it here
Use only one route with a parameter:
.state("person", {
url: "/person/:file",
....
});
Then in the template controller get the file parameter with $stateParams, load the html content with $http and put the result in a ng-bind-html tag attribute.
As discussed in comments here, we can use even resolve.
There is a working plunker
This could be the data.json
[
{
"id":1,
"name":"Someone 1"
},
{
"id":2,
"name":"Someone 2"
},
{
"id":3,
"name":"Someone 3"
}
]
And these state def would use that file to produce list and a detail. Parent state with resolve
.state('guys', {
url: "/route",
templateUrl:'guys.html',
controller:'listCtrl',
resolve: {
guys: ['$http', function($http){
return $http
.get("data.json")
.then(function(response){
return response.data;
})
}],
}
})
And child with the templating driven by passed id:
.state('guy', {
parent: 'guys',
url: "/:id",
controller:'MyCtrl',
templateProvider: function($templateRequest, $stateParams) {
var index = $stateParams.id;
var templateName = 'file' + index + '.html';
return $templateRequest(templateName);
},
})
And that should show how to use UI-Router with resolve
Check it here
See also
AngularJS - UI Router - Unable to use resolve to provide my controller with data
Angularjs ui-router abstract state with resolve
UI-Router will not resolve $http call
I would like to add new page into default ionic app with tabbed menu and display this page as the default page of the app.
Here is how I tried to do that:
I added new state into app.js
.state('home', {
url: '/home',
views: {
'home': {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
}
}
})
and set default router to home page
$urlRouterProvider.otherwise('/home');
And template file:
<ion-view title="Home">
<ion-content class="padding">
<h1>Home page</h1>
</ion-content>
</ion-view>
Now, if I am trying to go to http://myapp.loc/index.html#/home I got always black page without content.
What I'm doing wrong?
Thanks for any help.
EDIT:
In order to Error: [ng:areq] Argument 'HomeCtrl' is not a function, got undefined
I'm adding related code.
Added controllers:
angular.module('starter.controllers', [])
.controller('HomeCtrl', function($scope, $location) {
})
.controller('DashCtrl', function($scope) {
})
.controller('FriendsCtrl', function($scope, Friends) {
$scope.friends = Friends.all();
})
.controller('FriendDetailCtrl', function($scope, $stateParams, Friends) {
$scope.friend = Friends.get($stateParams.friendId);
});
Order in index.html is following
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/controllers/overall_stats.js"></script>
<script src="js/services.js"></script>
I would say, that solution here should be surprisingly simple:
Remove the view name 'home'. In fact change it to '' (empty string)
There is a working plunker with this change?
.state('home', {
url: '/home',
views: {
// instead of this
// 'home': {
// use this
'': {
templateUrl: 'tpl.home.html',
controller: 'HomeCtrl',
}
}
})
Why? Because most likely the index.html would look like this:
<body ng-app="myApp" >
...
<ion-nav-view></ion-nav-view>
</body>
And that means that the view name is "", almost like <ion-nav-view name=""></ion-nav-view>
Check that in action here
EXTEND based on the question extension
if we use ionic-like approach with separated file and module for controllers:
// inside of the index.html
<script src="js/controllers.js"></script>
// the controller.js
angular.module('starter.controllers', [])
We must be sure, that our app.js does contain that module as well:
angular.module('myApp', [
'ionic',
'starter.controllers' // this is a MUST
])