I have difficulties using <a href, so i try to find another workaround. The plan is to use ng-click to invoke an url, and reload the page using that url.
This is my html :
<li class="item" ng-click="go_to()">
<img src="img/ionic.png">
<p>Beginners Guide</p>
</li>
Which call :
app.controller("listController", ['$scope', '$location', function ($scope, $location) {
$scope.go_to = function () {
alert("a"); //CALLED
var url = "http://google.com";
$location.url(url); //NOT LOADED
}
}]);
The end goal is, i just want my apps to open the url when the <li> is clicked
Thanks a lot for your help
One simple way which always worked for me was :
<a href="...">
<li class="item" ng-click="go_to()">
<img src="img/ionic.png">
<p>Beginners Guide</p>
</li>
</a>
You can use
$window.location.href = 'http://google.com'
Full code should look like
app.controller("listController", ['$scope', '$location', '$window', function($scope, $location, $window) {
$scope.go_to = function() {
alert("a"); //CALLED
var url = "http://google.com";
$window.location.href = url;
};
}]);
Its better to use $stateProvider and you also need to add whitelist plugins to
access external resources.
Use $stateProvider like this
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'indexController'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'CenterListController'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:centerId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
cache:true,
controller: 'CenterDetailController'
}
}
})
.state('tab.manual-Location', {
url: '/manualLocation',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'ManualLocationController'
}
}
})
.state('tab.manual-Location-List', {
url: '/manualLocationList/:locationID',
views: {
'tab-account': {
templateUrl: 'templates/manualLocationList.html',
controller: 'ManualLocationListController'
}
}
})
.state('tab.manual-Location-Detail', {
url: '/manualLocationDetail/:centerId',
views: {
'tab-account': {
templateUrl: 'templates/manual-Location-Detail.html',
controller: 'ManualLocationDetailController'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
You could use $window.open(url, '_blank')
OR
You could look at this answer, in which I have made a such changes that you could redirect to other page, from ui-router state itself.
You can also customize ui-router by adding parameter external, it can be true/false.
$stateProvider
.state('external', {
url: 'http://www.google.com',
external: true
})
Then configure $stateChangeStart in your state & handle redirection part there.
Run Block
myapp.run(function($rootScope, $window) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
if (toState.external) {
event.preventDefault();
$window.open(toState.url, '_self');
}
});
})
Working Plunkr
The $location service is not designed to navigate away and reload the current page. It is designed for single page applications.
https://docs.angularjs.org/guide/$location
The $location service allows you to change only the URL; it does not
allow you to reload the page. When you need to change the URL and
reload the page or navigate to a different page, please use a lower
level API, $window.location.href.
If you are trying to navigate to a different page, use:
$window.location.href = "http://www.google.com";
If you are using ui-router. You can use <a ui-sref="" as a way to navigate to different routes. Which is really just a wrapper around $state.go
YOU CAN USE THE FOLLOWING CODE FOR THIS PROBLEM
$window.open("http://google.com", "_blank");
This will open the url in next tab
http://plnkr.co/edit/hfQ18sdHHzEgkF4vEYs5?p=preview
This is one of the working solution for your question
$scope.go_to = function() {
alert("a"); //CALLED
var url = "http://google.com";
$window.open(url, "_blank");
};
Finally found the culprit :)
Its because i commented this single code in my index :
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
After that, i just need to use a basic href
Related
I have userAccess flag in controller if it returns false i want hide all the application from user and redirect user to access.html with some access required form So with below code it throws error transition superseded, Any idea how to achieve this task with angularjs ui.router ?
mainCtrl.js
$scope.cookie = $cookies.get(jklHr');
var parts = $scope.cookie.split("|");
var uidParts = parts[7].split(",");
$scope.newUser._id = uidParts[0];
var userAccess = AuthService.getCurrentUser($scope.newUser._id);
if(!userAccess) {
console.log("Access Deinied");
$state.go('app.access');
}
app.js
angular.module('App', [
'ui.router',
'ui.bootstrap',
'ui.bootstrap.pagination',
'ngSanitize',
'timer',
'toastr',
'ngCookies',
]).config(function($stateProvider, $httpProvider, $urlRouterProvider) {
'use strict'
$urlRouterProvider.otherwise(function($injector) {
var $state = $injector.get('$state');
$state.go('app.home');
});
$stateProvider
.state('app', {
abstract: true,
url: '',
templateUrl: 'web/global/main.html',
controller: 'MainCtrl'
})
.state('app.home', {
url: '/',
templateUrl: 'view/home.html',
controller: 'MainCtrl'
})
.state('app.dit', {
url: '/dit',
templateUrl: 'view/partials/logs.html',
controller: 'LogsCtrl',
resolve: {
changeStateData: function(LogsFactory) {
var env = 'dit';
return LogsFactory.resolveData(env)
.then(function(response) {
return response.data
});
}
}
})
.state('app.access', {
url: '/access',
templateUrl: 'view/partials/access.html',
controller: 'AccessCtrl'
});
});
Create an interceptor, all http class will go thrown the interceptor. Once the "resolve" piece is executed and return 401 you can redirect to the login screen or 403 to the forbidden view.
https://docs.angularjs.org/api/ng/service/$http
The problem is that you are trying to change a state while a previous state change is still in course.
The ui-router has events for when a state change starts and ends.
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
});
So your redirect should be in there. Anyway I recommend you move that user check to a higher level in your app, like .run(), with some exception for the login states. That way you won't have to check in every controller individually.
Make sure you've most updated version of angularjs & angular-ui. If you're using older version then check compatibility of angular-ui version with your angular version. https://github.com/angular-ui/ui-router/issues/3246
If that doesn't work, add following line inside app.config
$qProvider.errorOnUnhandledRejections(false)
don't forget add dependency $qProvider in config function.
I am trying to make a nested views, here is the plunker https://embed.plnkr.co/oRMnMW4QoWwhSkm9maHf/. The state changes but the template not changes.
Can anyone correct me what have I done wrong
Goto Link > Second Nested .
On Clicking the button , state changes successfully but the content is not injected. I want the link page content to be replaced by the second-nested content
Try to put abstract:true on the 'father' root like:
var routerApp = angular.module('routerApp', ['ui.router','ncy-angular-breadcrumb']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home/list');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
abstract: true,
templateUrl: './partial-home.html'
})
// nested list with custom controller
.state('home.list', {
url: '/list',
templateUrl: './partial-home-list.html',
controller: function($scope) {
$scope.dogs = ['Bernese', 'Husky', 'Goldendoodle'];
}
})
.state('home.second', {
url: '/second',
templateUrl: './second.html',
});
});
routerApp.run(['$rootScope', '$state', function ($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
console.log("state Change")
});
}]);
but Remember .. if you put abstract: true .. the url is not a real one .. it's a prefix .. or as i call it .. a father of other routing ..so you can not call it in the .otherwise()
And in your link (and routing) of the second view .. just remove the .list ... so like this:
.state('home.second', { //<-- HERE .. REMOVE THE .list
url: '/second',
templateUrl: './second.html',
});
and in the link:
// AND HERE ..
<a ui-sref="home.second" class="btn btn-danger">Second Nested</a>
Answer is pretty simple - you are initializing 3rd level of nesting states but in ./partial-home-list.html you've didn't add ui-view directive.
Add <ui-view></ui-view> in ./partial-home-list.html and you will see that it works as you defined.
If you want to display home.list.second as separate page then define second state like this
.state('home.second', {
url: '/home/list/second',
templateUrl: 'second.html',
});
Remember to update ui-sref to home.second on button
--
Just to get nested breadcrumb I have not "nice" solution but will work.
-- Partial home list html
<div ng-if="state.current.name != 'home.list.second'">
<ul>
<li ng-repeat="dog in dogs">{{ dog }}</li>
</ul>
<div ncy-breadcrumb></div>
<a ui-sref="home.list.second" class="btn btn-danger">Second Nested</a>
</div>
<ui-view></ui-view>
App js
// nested list with custom controller
.state('home.list', {
url: '/list',
templateUrl: 'partial-home-list.html',
controller: function($scope, $state) {
$scope.state = $state;
$scope.dogs = ['Bernese', 'Husky', 'Goldendoodle'];
}
})
.state('home.list.second', {
url: '/second',
templateUrl: 'second.html',
});
I'm new angularjs student.
I'm using state provider in my project, i don't want to change this. Because the code is done.
Here is my code:
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.when('/SecondMain', '/SecondMain/OtherPageOne')
.when('/Main', '/Main/PageOne')
.otherwise("/notfound")
$stateProvider
.state('Main', {
abstract: true,
url: "/Main",
templateUrl: "/templates/Common/Main.html"
})
.state('SecondMain', {
abstract: true,
url: "/SecondMain",
templateUrl: "/templates/Common/SecondMain.html"
})
.state('notfound', {
url: "/NotFound",
templateUrl: "/templates/Common/NotFound.html"
})
.state('Main.PageOne', {
url: "/Main/PageOne",
templateUrl: "/templates/Main/PageOne.html"
})
.state('Main.PageTwo', {
url: "/Main/PageTwo",
templateUrl: "/templates/Main/PageTwo.html"
})
.state('SecondMain.OtherPageOne', {
url: "/SecondMain/PageOne",
templateUrl: "/templates/SecondMain/OtherPageOne.html"
})
.state('SecondMain.OtherPageTwo', {
url: "/SecondMain/PageTwo",
templateUrl: "/templates/SecondMain/OtherPageTwo.html"
})
angular
.module('inspinia')
.config(config)
.run(function ($rootScope, $state) {
$rootScope.$state = $state;
});
}
I want a logic like this: If the user put:
/Main/PageThree
This page does not exist, but the user start URL with
/Main
so that he need to go to -> /Main/PageOne
if the user put:
/Ma/PageOne
/Ma does not exist, the user starts URL totally wrong, so that he goes to -> /Notfound Basically if the user put /Main/WRONG_LINK, he go to /Main/PageOne . And if he does not start with /Main, he go to NotFound.
Can anyone help me please?
Thanks a lot!!!
You are missing this configuration
$urlRouterProvider.otherwise('/NotFound');
Just add this line if no matching route is found then it will redirect you to the /NotFound url
This answer is inspired by this answer.
First of all, you will have to make the Main state non-abstract, so that it can be visited. Then, you can write config related to where you want to redirect (for example, I've used redirectTo with the state):
$stateProvider
.state('Main', {
redirectTo: "Main.PageOne",
url: "/Main",
templateUrl: "/templates/Common/Main.html"
})
// ... Rest of code
So, whenever the URL is changed to /Main, this state will get activated. The second config will be to create a listener for $stateChangeStart event as follows:
angular
.module('inspinia')
.config(config)
.run(function ($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(evt, to, params) {
if (to.redirectTo) {
evt.preventDefault();
$state.go(to.redirectTo, params, { location: 'replace' })
}
});
});
Now, if a URL like /Ma/* is hit, it automatically be redirected to /NotFound. And if a URL like /Main is hit, it will redirect to /Main/PageOne.
You can follow up on further discussion on this link for any kind of troubleshooting.
Clearly read the statements below
Why are you using this line?
when('/Main', '/Main/PageOne')
For your redirection problem, have a look at the below state
.state('Main', {
abstract: true,
url: "/Main",
templateUrl: "/templates/Common/Main.html"
})
abstract: true ==> This denotes that this particular state is an abstract which can never be activated without its child.
SOURCE: ui-router js code. Refer the below snippet
Since you have this main state as abstract, you are redirected to the otherwise.
Hope this
I am using UI-Router to navigate to detailed view. It changes state correctly and passes parameters correctly, yet the url address in the browser stays unchanged. I would like to display the passed params in the url.
app.js
'use strict';
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
function($stateProvider, $urlRouterProvider,$locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'partials/listView.html'
})
.state('list', {
url: '/',
templateUrl: 'partials/listView.html'
})
.state('detail', {
url: '/detail/:key',
params: {
key: { value: "" }
},
templateUrl: 'partials/detailView.html',
controller: 'DetailController'
})
// use the HTML5 History API
$locationProvider.html5Mode(true);
}]);
Controller function to go to the detail state:
myApp.controller('MainContr', [ '$scope', '$http', '$location', '$state',
'$filter','$rootScope', MainContr ]);
function MainContr($scope, $http, $location, $state, $filter,$rootScope) {
$scope.goDetailView= function(key){
console.log("trying to change url ");
// changes state correctly, and passes params to DetailController,
// but does not change browser address url.
// How can I update the url in browser here?
$state.go('detail',
{key: $scope.selectedPDFKey},
{
location:true
});
}
}
// detail view
myApp.controller('DetailController', [ '$scope', '$stateParams'
DetailController ]);
function PDFDetailController($scope,$state)
{
$scope.currentKey=$state.params.key;
}
If I remove params in $state.go('detail'), the url in browser address bar is replaced. How can I get url in browser address bar replaced as well when I pass parameters in $state.go(). Thank you.
Issue was fixed when state was changed to use query in url as:
.state('detail', {
url: '/detail?key',
params: {
key: { value: "" }
},
templateUrl: 'partials/detailView.html',
controller: 'DetailController'
})
I came across this, but in my case it was just a missing / at the beginning of the url. So this is wrong:
.state('detail', {
url: 'detail/:key',
templateUrl: 'tpl.html'
});
And this is correct/working:
.state('detail', {
url: '/detail/:key',
templateUrl: 'tpl.html'
});
I dont needed any <base> tags in my <head> at all. My application is in a subfolder called /app.
By default - UI-Router will always show the param in address bar, if is defined in the url (not just in params : {} option)
To prove it, there is a plunker with your scenario, which does what you would expect - http://plnkr.co/edit/9uBlhNoNqZsjAJEdIhYa?p=preview
Links
<a ui-sref="list">
<a ui-sref="detail({key:1})">
<a ui-sref="detail({key:22})">
A state def (as yours)
.state('list', {
url: '/',
templateUrl: 'tpl.html',
controller: 'ParentCtrl',
})
.state('detail', {
url: '/detail/:key',
params: {
key: { value: "" }
},
templateUrl: 'tpl.html',
controller: 'ChildCtrl',
});
Check it here
(you can run it in separate window, by clicking the icon in the top right corner - and see the address bar with a key param)
I am trying to do what was essentially answered here Unable to open bootstrap modal window as a route
Yet my solution just will not work. I get an error
Error: [$injector:unpr] Unknown provider: $modalProvider <- $modal
My app has the ui.bootstrap module injected - here is my application config
var app = angular.module('app', ['ui.router', 'ui.bootstrap','ui.bootstrap.tpls', 'app.filters', 'app.services', 'app.directives', 'app.controllers'])
// Gets executed during the provider registrations and configuration phase. Only providers and constants can be
// injected here. This is to prevent accidental instantiation of services before they have been fully configured.
.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
// UI States, URL Routing & Mapping. For more info see: https://github.com/angular-ui/ui-router
// ------------------------------------------------------------------------------------------------------------
$stateProvider
.state('home', {
url: '/',
templateUrl: '/views/index',
controller: 'HomeCtrl'
})
.state('transactions', {
url: '/transactions',
templateUrl: '/views/transactions',
controller: 'TransactionsCtrl'
})
.state('login', {
url: "/login",
templateUrl: '/views/login',
controller: 'LoginCtrl'
})
.state('otherwise', {
url: '*path',
templateUrl: '/views/404',
controller: 'Error404Ctrl'
});
$locationProvider.html5Mode(true);
}])
I have reduced my controller to the following:
appControllers.controller('LoginCtrl', ['$scope', '$modal', function($scope, $modal) {
$modal.open({templateUrl:'modal.html'});
}]);
Ultimately, what I am hoping to achieve is when login is required not actually GO to the login page, but bring up a dialog.
I have also tried using the onEnter function in the ui-router state method. Couldn't get this working either.
Any ideas?
UPDATE
Ok - so as it turns out, having both ui-bootstrap.js AND ui-bootstrap-tpls breaks this - After reading the docs I thought you needed the templates to work WITH the ui-bootstrap. though it seems all the plunkers only load in the ..tpls file - once I removed the ui-bootstrap file my modal works...Am i blind? or doesn't it not really say which one you need in the docs on github? -
Now i just need to figure out how to prevent my url from actually going to /login, rather than just show the modal :)
update 2
Ok, so by calling $state.go('login') in a service does this for me.
Hi I had a hard time getting through the similar problem.
However, I was able to resolve it.
This is what you would probably need.
app.config(function($stateProvider) {
$stateProvider.state("managerState", {
url: "/ManagerRecord",
controller: "myController",
templateUrl: 'index.html'
})
.state("employeeState", {
url: "empRecords",
parent: "managerState",
params: {
empId: 0
},
onEnter: [
"$modal",
function($modal) {
$modal.open({
controller: "EmpDetailsController",
controllerAs: "empDetails",
templateUrl: 'empDetails.html',
size: 'sm'
}).result.finally(function() {
$stateProvider.go('^');
});
}
]
});
});
Click here for plunker. Hope it helps.
I'm working on something similar and this is my solution.
HTML code
<a ui-sref="home.modal({path: 'login'})" class="btn btn-default" ng-click="openModal()">Login</a>
State configuration
$stateProvider
// assuming we want to open the modal on home page
.state('home', {
url: '/',
templateUrl: '/views/index',
controller: 'HomeCtrl'
})
// create a nested state
.state('home.modal', {
url: ':path/'
});
Home controller
//... other code
$scope.openModal = function(){
$modal.open({
templateUrl: 'path/to/page.html',
resolve: {
newPath: function(){
return 'home'
},
oldPath: function(){
return 'home.modal'
}
},
controller: 'ModalInstanceController'
});
};
//... other code
Finally, the modal instance controller.
This controller synchronizes the modal events (open/close) with URL path changes.
angular.module("app").controller('ModalInstanceController', function($scope, $modalInstance, $state, newPath, oldPath) {
$modalInstance.opened.then(function(){
$state.go(newPath);
});
$modalInstance.result.then(null,function(){
$state.go(oldPath);
});
$scope.$on('$stateChangeSuccess', function () {
if($state.current.name != newPath){
$modalInstance.dismiss('cancel')
}
});
});
You may create a state with the same templateUrl and controller as your page where you want to show the modal, adding params object to it
$stateProvider
.state('root.start-page', {
url: '/',
templateUrl: 'App/src/pages/start-page/start-page.html',
controller: 'StartPageCtrl'
})
.state('root.login', {
url: '/login',
templateUrl: 'App/src/pages/start-page/start-page.html',
controller: 'StartPageCtrl',
params: {
openLoginModal: true
}
})
And in controller of the page, use this parameter to open the modal
.controller("StartPageCtrl", function($scope, $stateParams) {
if ($stateParams.openLoginModal) {
$scope.openLoginModal();
}
I found a handy hint to get this working. There are probably caveats, but it works for me. You can pass a result still but I have no need for one.
Using finally instead of the then promise resolve sorted this for me. I also had to store the previous state on rootScope so we knew what to go back to.
Save previous state to $rootScope
$rootScope.previousState = 'home';
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from, fromParams){
$rootScope.previousState = from.name;
})
State using onEnter
$stateProvider.state('contact', {
url: '/contact',
onEnter: function ($state, $modal, $rootScope){
$modal.open({
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
}).result.finally(function(){
$state.go($rootScope.previousState);
})
}
});