I am trying to use Angular UI router in my application. When I initialise the UI router instead of getting say, localhost:8000/#/ I get localhost:8000/#!#%2F.
My app.js is as follows:
angular
.module('quiz',['ngMaterial',
'ngMessages',
'ngCookies',
'ngResource',
'quiz.routes'
]).config(function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
});
angular
.module('quiz.routes',['ui.router']);
In my quiz.routes.js I have:
(function () {
angular
.module('quiz.routes')
.config(config);
function config($urlRouterProvider,$stateProvider){
$stateProvider
.state('register',{
url: '',
templateUrl: '/static/templates/register.html'
});
}
})();
So instead of the trailing slash I get !#%2F in my URL. Why is this?
Assuming that you are using Angular version 1.6, then this is likely because of the changes made to the default hashPrefix which is now set to !. To fix, you need to inject $locationProvider into your module's config block and reset the default hashPrefix back to the empty string.
$locationProvider.hashPrefix('')
This was reported as a bug here, although it turns out that it was by design and changed intentionally.
Related
I'm trying to get lazy-loaded Angular modules working with Webpack, but I'm having some difficulties. Webpack appears to generate the split point correctly, because I see a 1.bundle.js getting created that contains the code for the child app, but I don't see any request for 1.bundle.js when I load the page, and the child app doesn't initialize. The console.log never seems to fire, and it doesn't even appear to get to the point where $oclazyload would initialize the module.
There are a few points where I am confused.
1) Will webpack make the request to the server, or do I have to load the second bundle manually? (I've tried both, and neither works)
2) If I do need to load the bundles manually, in what order should they be loaded?
3) The third argument to require.ensure supposedly lets you control the name of the bundle, but the bundle is named 1.bundle.js no matter what string I pass.
4) Why can't I step through the code inside the require.ensure block in the debugger? When I do so I end up looking at this in the Chrome source view:
undefined
/** WEBPACK FOOTER **
**
**/
(Code Below)
Main entry point code:
'use strict';
import angular from 'angular';
import 'angular-ui-router';
import 'oclazyload';
angular.module('parentApp', [
'ui.router',
])
.config(['$urlRouterProvider', '$locationProvider', ($urlRouterProvider, $locationProvider) => {
$urlRouterProvider
.otherwise('/');
$locationProvider.html5Mode(true);
}])
.config(['$stateProvider', ($stateProvider) => {
$stateProvider
.state('child-app', {
url: '/child-app',
template: '<child-app></child-app>',
resolve: {
loadAppModule: ($q, $ocLazyLoad) => {
return $q((resolve) => {
require.ensure(['./child-app/app.js'], (require) => {
let module = require('./child-app/app.js');
console.log(module);
$oclazyload.load({name: 'childApp'});
resolve(module.controller);
});
})
}
},
controller: function() {
}
})
}]);
Child app:
'use strict';
import childAppTemplateURL from '../templates/child-app.html';
import childAppController from './controllers/childAppController';
export default angular.module('parentApp.childApp', [])
.component('applicationListApp', {
templateUrl: childAppTemplateURL,
controller: childAppController
});
The problem was unrelated to the require.ensure implementation. It was caused by some weirdness in the way ocLazyLoad is packaged (https://github.com/ocombe/ocLazyLoad/issues/179). The fix in my case was simple, I just added 'oc.lazyLoad' to the module dependencies.
angular.module('parentApp', [
'ui.router',
'oc.lazyLoad'
])
To answer two of my own questions, Webpack does indeed make a request to the server for the bundle, and you do not have to manually load the bundle. One gotcha that really confused me: the resolve block will fail silently if it contains a promise that won't resolve. In my case $ocLazyLoad.load() was failing, but there was no indication of the failure. The only clue was that the state provider wasn't adding the <child-app></child-app> markup to the DOM, which meant that it was actually initializing the state.
I followed a tutorial on how to organize and Angular project. I have a ng directory that contains all my controllers, services and my routes.js. This is then bundled all together into an app.js by my gulp config.
My module.js is like this:
var app = angular.module('app', [
'ngRoute',
'ui.bootstrap'
]);
Here's a bit of my routes.js:
angular.module('app')
.config(function ($routeProvider) {
.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
});
Here's what my working LoginCtrl looks like:
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
$scope.login = function(username, password) {
...
}
})
The tutorial didn't make use of any Angular modules and I wanted to try one out. I added ui.bootstrap to my page from a CDN and try to change the LoginCtrl to:
angular.module('app')
.controller('LoginCtrl', function($scope, $uibModal, UserSvc) {
...
})
But this throws me the following error:
"Error: [$injector:unpr] Unknown provider: $templateRequestProvider <- $templateRequest <- $uibModal
What is causing this error? In every tutorial I find this seems to be how they load a module, the only difference I see is that the tutorial don't seem to be using a router.
PS: Note that if I use an empty module list [] I get the exact same error. If I use a non-existing module ['helloworld'] I get an errorModule 'helloworld' is not available'. So I'm concluding that my `ui.bootstrap' module is indeed available.
EDIT: Plunker fiddle here: http://plnkr.co/edit/FWHQ5ZDAByOWsL9YeMUH?p=preview
angular route is another module you should not only include but also use like this
in the app module creation
means DI of route
angular.module('app', ['ngRoute']);
Please go through the angular route doc
Remove ['ui.bootstrap'] form controller. You should add dependencies only one time but you add it twice so the second dependency list override the first one.
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
... })
your routes snippet looks wrong, you should be hanging the when call off $routeProvider and maybe declare $routeProvider as an injected val if it's not being picked up e.g.
angular.module('app')
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
}]);
I have checked your link. I think there is a serious issue with angular and ui bootstrap version.In ui-boostrap dashboard, it is written that 0.12.0 is the last version that supports AngularJS 1.2.x. I have tried with all combinations but it doesn't work with your angular version.
I suggest you to change angular version to latest and ui-bootstrap version to latest so it will work.
Please check out this working Plukr
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.js'></script> //change this to latest also.
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.0.3/ui-bootstrap.min.js'></script>
<script src='./app.js'></script>
If you want to go with your angular version only. I'd request you to do some R&D. Try with different versions of ui-bootstrap. still if it doesn't work you can make PR.
I am kind of new to the AngularJS framework and I am trying to migrate my test project using the standard router to use the UI-router, but I get the following error:
Error: [ng:areq] Argument 'mainCtrl' is not a function, got undefined
What I have done so far is:
Controller:
// mainCtrl.js
angular.module("sm-web")
.controller('mainCtrl',['$scope',
function($scope) {
...
}]);
Router:
angular.module('sm-web', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function( $stateProvider, $urlRouterProvider ) {
$urlRouterProvider.otherwise('root');
$stateProvider
.state('root', {
url: '',
templateUrl: path + 'ng/sm/view/main.html',
controller: 'mainCtrl'
});
}]);
Index:
<body ng-controller="mainCtrl">
<main-menu></main-menu>
<div class="container">
<div ui-view></div>
</div>
</body>
This works when I use the standard router, but not with the UI-router. Does anyone have any idea of what I am doing wrong?
It seems you have an issue w/the order you declare things. For you to declare the module "sm-web" you need to do this:
angular.module('sm-web', ['ui.router']);
Note that the presence of that 2nd array argument is what tells Angular that you're declaring the module (eg. creating a new module). When you leave that 2nd argument out, you're retrieving the module you previously declared.
So with that in mind, look at how it all is coming together in your code:
To declare the controller, you retrieve the module "sm-web" (by leaving off the 2nd array arg).
When configuring the router states, you declare a new module "sm-web". But note that immediately after you declare this new module, you try to register a state with the controller named "mainCtrl" -- but that doesn't exist yet.
You need to create the module somewhere before doing all of the above. After creating the module, then register the controller on the module. Finally, with the controller defined, then you can register the state that uses the controller.
There's too many ways to solve this ordering problem, so I'm not going to suggest anything further. It depends on what files the code lives in and the order you load those files in index.html.
In order to avoid your problem change your code by the following code:
// mainCtrl.js
angular.module("sm-web")
.controller('mainCtrl',['$scope',
function($scope) {
...
}]);
Hi I have am trying to re direct the page to another route with parameter
like this passing id as a parameter.
$location.path('/api/po/'+id);
What is the proper way to re direct to another page using router and parameter? My module, controller etc all are working fine. Just having problem re directing.
Thaks
take a look at this ui router to me is the better way to build a function that move you application from a view to another one. It's really easy to use and very rich of useful method.
Follow these steps
Install ui-router using bower
Include angular-ui-router.js in your index.html
Add 'ui.router' to your main module's list of dependencies
Add a ui-view directive to the some in your html
Set up your states in the module config, following is an example how:
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html"
})
.state('route2', {
url: "/route2",
templateUrl: "route2.html"
})
})
Refer this in case of doubt.
I want to extract data from current URL and use it in controller.
For example I have this url:
app.dev/backend/surveys/2
Bits that I want to extract:
app.dev/backend/ :type / :id
Is there anything in Angular that could help me with this task ?
To get parameters from URL with ngRoute . It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.
The solution for the question:
// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
// configure the routing rules here
$routeProvider.when('/backend/:type/:id', {
controller: 'PagesCtrl'
});
// enable HTML5mode to disable hashbang urls
$locationProvider.html5Mode(true);
})
.controller('PagesCtrl', function ($routeParams) {
console.log($routeParams.id, $routeParams.type);
});
If you don't enable the $locationProvider.html5Mode(true);. Urls will use hashbang(/#/).
More information about routing can be found on official angular $route API documentation.
Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.
You could inject $routeParams to your controller and access all the params that where used when the route was resolved.
E.g.:
// route was: app.dev/backend/:type/:id
function MyCtrl($scope, $routeParams, $log) {
// use the params
$log.info($routeParams.type, $routeParams.id);
};
See angular $routeParams documentation for further information.
Better would have been generate url like
app.dev/backend?type=surveys&id=2
and then use
var type=$location.search().type;
var id=$location.search().id;
and inject $location in controller.
In your route configuration you typically define a route like,
.when('somewhere/:param1/:param2')
You can then either get the route in the resolve object by using $route.current.params
or in a controller, $routeParams. In either case the parameters is extracted using the mapping of the route, so param1 can be accessed by $routeParams.param1 in the controller.
Edit: Also note that the mapping has to be exact
/some/folder/:param1
Will only match a single parameter.
/some/folder/:param1/:param2
Will only match two parameters.
This is a bit different then most dynamic server side routes. For example NodeJS (Express) route mapping where you can supply only a single route with X number of parameters.
ex:
url/:id
var sample= app.controller('sample', function ($scope, $routeParams) {
$scope.init = function () {
var qa_id = $routeParams.qa_id;
}
});
Just inject the routeParams service:
http://docs.angularjs.org/api/ngRoute.$routeParams