I have a small AngularJS test app and am running http-server. I am using ui-router. When I load localhost:8080 my angular component works fine. When I click on <a ui-sref="new">New</> I go to localhost:8080/new and the new component loads fine. However, when I reload the page, the product-details component doesn't load
app.js
'use strict';
angular
.module('productApp', [
'ui.router',
'ProductComponents',
])
.config([
'$httpProvider',
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
'$compileProvider',
function($httpProvider, $locationProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$compileProvider.debugInfoEnabled('<%= Rails.env.development? %>');
var token = document.querySelector('meta[name="csrf-token"]');
if(angular.isElement(token)){
$httpProvider.defaults.headers.common['X-CSRF-Token'] = token.content;
}
$httpProvider.useApplyAsync(true);
$httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike';
// For any unmatched url, redirect to /state1
$urlRouterProvider
.otherwise("/");
$stateProvider
.state('root', {
url: "/",
template: '<product-index meta="meta"></product-index>'
})
.state('new', {
url: "/new",
template: '<product-new></product-new>'
})
}])
index.html
<!DOCTYPE html>
<html>
<head>>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="//unpkg.com/#uirouter/angularjs/release/angular-ui-router.min.js"></script>
<script src="select.js"></script>
<script src="product_components.js"></script>
<script src="product_index.js"></script>
<script src="product_new.js"></script>
<script src="product_details.js"></script>
<script src="app.js"></script>
<base href="/">
</head>
<body>
<div ng-app="productApp">
<ui-view></ui-view>
</div>
</body>
</html>
product-new.js
'use strict';
angular
.module('ProductComponents')
.component('productNew', {
bindings:{
},
templateUrl: "new.html",
controllerAs: 'prodNew',
controller: function(){
var prodNew = this;
prodNew.product = { name: 'Test Product' };
}
}
)
new.html
<h2>Products</h2>
<product-details product="prodNew.product"></product-details>
product-details.js
angular
.module('ProductComponents')
.component('productDetails', {
bindings:{
product: '=product',
},
templateUrl: "details.html",
controllerAs: 'prodDetails',
controller: [
'$filter',
// '$http',
function(
$filter,
// $http,
){
var prodDetails = this;
...
Related
When I start my asp.net mvc application (www.mysite.com), the home controller index action is loaded.
This action serves a view, and in that view my AngularJS app is loaded.
However, my AngularJS app wants to be started at www.mysite.com/#!/
Is there a way to force this, that when you go to the root that it gets redirected to /#!/ ?
What I have now is this:
<system.webServer>
<defaultDocument enabled="true">
<!-- this line enables default documents for a directory -->
<files>
<clear/>
<!-- removes the existing default document list -->
<add value="/#!/"/>
</files>
</defaultDocument>
but as you can guess this doesn't work.
I tested it at my local IIS and at Azure.
EDIT
To clarify: If I don't put the /#!/ at the end or the url, Angular does not kick in. Maybe that is the problem, that I do not have my config right?
my home state is this:
.state(appConfig.routes.home, {
url: "/",
views: {
'content': { templateUrl: "/Js/views/home/home.html", controller: 'ikvhomecontroller as vmhome' },
'homeheader#index.home': { templateUrl: "/Js/views/shared/sharedheader.html", controller: 'sharedheadercontroller as vmshhe' }
}
})
This is my config:
(function () {
'use strict';
angular.module(Main.config.name, [
// Angular modules
'ngResource',
'ngSanitize',
// Custom modules
// 3rd Party Modules
'ui.router',
'ngAnimate'
])
.constant('appConfig', Main)
.config(['$locationProvider', '$stateProvider', 'appConfig', '$httpProvider', '$urlRouterProvider', function ($locationProvider, $stateProvider, appConfig, $httpProvider, $urlRouterProvider) {
console.log('yep, I am at .config');
if (appConfig.useHtml5Mode)
$locationProvider.html5Mode(true);
else {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
};
$urlRouterProvider.otherwise("/");
$urlRouterProvider.when('/', 'index.home');
$stateProvider
.state('index', {
url: "",
views: {
"#": { templateUrl: "/Js/views/main.html" },
"header#index": { templateUrl: "/Js/views/header.html", controller: "menucontroller as vm" },
'content#index': { templateUrl: "/Js/views/content.html" },
"footer#index": { templateUrl: "/Js/views/footer.html" }
}
})
.state(appConfig.routes.home, {
url: "/",
views: {
'content': { templateUrl: "/Js/views/home/home.html", controller: 'homecontroller as vmhome' },
'homeheader#index.home': { templateUrl: "/Js/views/shared/sharedheader.html", controller: 'sharedheadercontroller as vmshhe' }
}
});
}])
.run([
'$http',
'$state',
'$rootScope',
'$templateCache',
function ($http, $state, $rootScope, $templateCache) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
$rootScope.$on('$locationChangeSuccess', function (evt) {
console.log(evt);
});
$templateCache.removeAll();
}]);
})();
This is the html in the browser:
<div id="main" ui-view>
<div class="imgwrapper"><img src="/Images/iloading.gif" /></div>
</div>
<script src="/Scripts/jquery-2.2.0.js"></script>
<script src="/Scripts/modernizr-2.8.3.js"></script>
<script src="/Scripts/moment-with-locales.js"></script>
<script src="/Scripts/uihelpers/currencykeydown.js"></script>
<script src="/Scripts/uihelpers/datekeydown.js"></script>
<script src="/Scripts/uihelpers/labeltitleclick.js"></script>
<script src="/Scripts/uihelpers/textareagrow.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-route.js"></script>
<script src="/Scripts/angular-resource.js"></script>
<script src="/Scripts/angular-sanitize.js"></script>
<script src="/Scripts/angular-animate.js"></script>
<script src="/Scripts/angular-locale_nl-nl.js"></script>
<script src="/Scripts/angular-ui-router.js"></script>
<script src="/Scripts/config.js"></script>
<script src="/Scripts/App.js"></script>
<script src="/Scripts/helpers/calcutils.js"></script>
<script src="/Scripts/helpers/dateutils.js"></script>
<script src="/Scripts/helpers/SelectHelper.js"></script>
and the rest of my custom code goes here
you should modify your 'route.config.js' in angularjs like as -
angular.module('yourModuleName').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider.
state('login', {
url: 'login',
templateUrl: '/path/to your login page',
});
$urlRouterProvider.otherwise("/");
$urlRouterProvider.when('/', 'login');
}
]);
This will automatically route your page to localhost/#!/login when you start your application.
I want to create angular nested routes in my application using angular-ui-router with multi sub-modules;
In "ui-router" we can use multi views in our main app config as $stateProvider, but can't switch between sub-modules when you are in other module.
For example when you are in "module1" you can not state to "module2".
So, How can I switch between my modules?
In this application you can route between sub modules easily:
Create main application "mainApp.js"
angular.module("mainApp", [
"ui.router"
]);
angular.module("mainApp").config([
"$stateProvider", "$urlRouterProvider",
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("/", {
url: "/",
templateUrl: "/Application/Partials/home.html"
});
}
]);
Create "index.html" for your mainApp:
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<title>Angular Nested Routes with angula-ui-route</title>
</head>
<body>
<fieldset>
<legend>main menu</legend>
<a ui-sref="/">home</a>
</fieldset>
<ui-view></ui-view>
<script src="/Scripts/jquery-2.1.4.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-ui-router.js"></script>
<!--Main Module-->
<script src="/Application/app.js"></script>
</body>
</html>
Create your Partials "home.html"
<h1>Home</h1>
Add "registerStateApp" in your project
angular.module("registerStateApp", []);
angular.module("registerStateApp").provider("$registerState", function ($stateProvider) {
var routes = [];
this.$set = function (stateProvider) {
var satetProviders = {
states: stateProvider
}
routes.push(satetProviders);
};
this.$get = function () {
return angular.forEach(routes, function (route) {
angular.forEach(route.states, function (state) {
$stateProvider.state(state.state, {
parent: state.parent,
moduleName: parent,
stateName: child,
name: state.pageName,
url: state.url,
views: state.views,
pageInfo: state.pageInfo
});
});
});
};
});
Update "mainApp.js" & inject "registerStateApp" in your main application
angular.module("mainApp", [
"ui.router",
"registerStateApp"
]);
angular.module("mainApp").config([
"$stateProvider", "$urlRouterProvider", "$registerStateProvider",
function($stateProvider, $urlRouterProvider, $registerStateProvider) {
$urlRouterProvider.otherwise("/");
//registerStateApp
$registerStateProvider.$get();
//your main application routes
$stateProvider
.state("/", {
url: "/",
templateUrl: "/Application/Partials/home.html"
});
}
]);
Create your sub-modules
angular.module("module1", []);
angular.module("module1").config(["$registerStateProvider",
function($registerStateProvider) {
//This is your routing in sub module
var stateProvider = [{
name: "module1",
state: "module1.page1",
url: "/module1",
views: {
"module1": {
templateUrl: "/Application/Modules/Module1/Partials/page1.html"
}
}
}];
$registerStateProvider.$set(stateProvider);
}
]);
//module2
angular.module("module2", []);
angular.module("module2").config(["$registerStateProvider",
function($registerStateProvider) {
var stateProvider = [{
name: "module2",
state: "module2.page1",
url: "/module2",
views: {
"module2": {
templateUrl: "/Application/Modules/Module2/Partials/page1.html"
}
}
}];
$registerStateProvider.$set(stateProvider);
}
]);
Create sub-module main view
<!DOCTYPE html>
<html ng-app="module1">
<head>
<title>module1</title>
</head>
<body>
<h1>This is module1</h1>
<button ui-sref="module2.page1">go to module2 page 1</button>
<div ui-view="module1"></div>
</body>
</html>
<!--module2-->
<!DOCTYPE html>
<html ng-app="module2">
<head>
<title>module2</title>
</head>
<body>
<h1>This is module2</h1>
<button ui-sref="module1.page1">go to module1 page 1</button>
<div ui-view="module2"></div>
</body>
</html>
Add your sub-modules state in your main app "mainApp.js"
angular.module("mainApp", [
"ui.router",
"registerStateApp",
"module1",
"module2"
]);
angular.module("mainApp").config([
"$stateProvider", "$urlRouterProvider", "$registerStateProvider",
function($stateProvider, $urlRouterProvider, $registerStateProvider) {
$urlRouterProvider.otherwise("/");
$registerStateProvider.$get();
$stateProvider
.state("/", {
url: "/",
templateUrl: "/Application/Partials/home.html"
})
.state("module1", {
url: "/module1",
templateUrl: "/Application/Modules/Module1/index.html"
})
.state("module2", {
url: "/module2",
templateUrl: "/Application/Modules/Module2/index.html"
});
}
]);
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
All works fine if I don't inject into controller "getChildrenNumber", after then I get the error from $injector.
I've read even this https://docs.angularjs.org/error/$injector/unpr, but it seems not be one of that cases
HTML (index.html):
<html class="no-js" ng-app="myApp" ng-strict-di>
.
.
.
<script src="jsLib/angular_v1.4.js" type="text/javascript"></script>
<script src="jsLib/angular-ui-router.min.js" type="text/javascript"></script>
<script src="jsLib/angular-ui-router-statehelper.min.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="routes.js" type="text/javascript"></script>
routes.js:
var config = ["$urlRouterProvider", "$stateProvider", "$locationProvider", function($urlRouterProvider, $stateProvider, $locationProvider){
$urlRouterProvider.otherwise("/multi");
$stateProvider
.state("multi",{
url: "/multi",
views: {
"": {
templateUrl: "multipleView.htm",
controller: "MainCTRL",
controllerAs: "ctrl"
},
"viewA#multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL",
controllerAs: "ctrl"
},
"viewB#multi": {
templateUrl: "app/templates/login.htm",
controller: ["$scope", "getChildrenNumber", function($scope, getChildrenNumber){
$scope.nameApp = "nameAppChanged";
$scope.children = getChildrenNumber + " Miao";
}]
}
},
resolve: {
getChildrenNumber: ["$http", function($http){
return "Some response from an API";
}]
}
});
}];
angular
.module("myApp")
.config(config);
app.js:
angular
.module("myApp", ["ui.router"])
.controller("MainCTRL", ["$scope", "getChildrenNumber", function($scope, getChildrenNumber){
this.nameApp = "myApp";
$scope.children = getChildrenNumber;
}]);
You are implementing it the wrong way..
Firstly, in routes.js
$stateProvider
.state("multi",{
url: "/multi",
views: {
// Views Code here //
},
resolve: {
getChildrenNumber: getChildrenNumber
}
});
}];
then you have to create your factory:
angular.module('myApp')
.factory('children', ['$http', function ($http) {
return {
getChildrenNumber: getChildrenNumber
};
function getChildrenNumber() {
return "Some response from an API";
}
}]);
After this you can inject it in your controller as children
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.