Ionic + Angular ui-sref not generating href - javascript

I'm working on passing parameters in a url. As far as I know everything is setup correct to set the baseFilter url parameter with the vm.all property but every time I click the link nothing happens. I also inspected the generated html and I see a ui-sref and not a href tag. Any help is appreciated
router.js
(function () {
'use strict';
angular.module('app').config(routing);
/* #ngInject */
function routing($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/home.html',
controller: 'HomeContentController as vm'
})
.state('eventsList', {
url: '/eventsList/:baseFilter',
templateUrl: 'events-list/events-list.html',
controller: 'EventsListController as vm'
});
$urlRouterProvider.otherwise('/home');
}
})();
This is the a tag in my home.html
<a class="item" ui-sref="eventsList({baseFilter: vm.all})">
HomeController.js
(function () {
'use strict';
angular.module('app').controller('HomeContentController', HomeContentController);
/* #ngInject */
function HomeContentController($scope, $log, $ionicSideMenuDelegate, $ionicPopup, $state, rxEventsService, rxRequests, $cordovaGeolocation) {
// Assign variable `vm` to `this` to reflect that this is a view-model.
var vm = this;
vm.all = "all";
// Bindable Properties
vm.promptUnavailable = promptUnavailable;
// Controller Initialization
function init() {
console.log('init HomeContentController');
}
init();
// Bindable Events
function promptUnavailable(feature) {
$ionicPopup.alert({
title: 'Unavailable Feature',
template: feature + ' is unavailable in this Alpha release'
});
}
}
})();

If you set the correct value of vm.all your code should work fine.
angular
.module('app', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeContentController as vm'
})
.state('eventsList', {
url: '/eventsList/:baseFilter',
templateUrl: 'events-list.html',
controller: 'EventsListController as vm'
});
$urlRouterProvider.otherwise('/home');
})
.controller('HomeContentController', function () {
var vm = this;
vm.all = 1;
})
.controller('EventsListController', function ($stateParams) {
var vm = this;
console.log($stateParams);
});
I have created a JSBin using your code and it works fine. If you see the value logged in console log, it has correct value of $stateParams. https://jsbin.com/qebimeh/1/edit?html,js,console,output

Related

UI router change templateUrl on click

Im trying to create a dynamic UI router when everytime you click a button it needs to return the templateUrl with the $stateParams.currentFloor changes only so it can get updated in the view on the screen.
Currently I have:
My setup:
app.config(function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
views: {
"menu-view": {
templateUrl: 'partials/menu.html'
},
"map-view": {
controller: 'mapViewController',
templateUrl: function ($stateParams) {
return 'partials/floors/floor-' + $stateParams.currentFloor + '.html'
}
}
}
})
});
My controller what needs to hold the data and pass it in the templateUrl function
app.controller('mapViewController', function ($scope, $stateParams) {
$scope.currentFloor = $stateParams.currentFloor;
$scope.currentFloor = 1;
$scope.addOne = function () {
$scope.currentFloor = $scope.currentFloor + 1;
return $stateParams.currentFloor = $scope.currentFloor;
};
});
And just simple a function what adds +1 to the scope everytime on a click
<button ng-click="addOne()"></button>
I think I'm pretty close but I have a hard time passing the data from my controller to the function what needs to change the templateUrl
Check the updated plunker here
One possible solution :
var app = angular.module('testTool', ['ui.router'])
.config(function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/1');
$stateProvider
.state('home', {
url: '/:currentFloor',
views: {
"menu-view": {
templateUrl: 'menu.html'
},
"map-view": {
templateUrl: function ($stateParams) {
return 'floor-' + $stateParams.currentFloor + '.html'
},
controller: 'mapViewController'
},
}
})
})
.controller('mapViewController', function($scope, $stateParams, $state) {
$scope.addOne = function() {
$state.go('home', {currentFloor : parseInt($stateParams.currentFloor) + 1}, {reload: true})
};
});
Add param 'currentFloor in url params (url:'/:currentFloor'). Then reload state with this params : $state.go('home', {currentFloor : 2}, {reload: true})
Option reload:true is important for ui router reload the state when your are on the same state.
I suggest you to use resolve function if you need to do some work between $stateParams and object in your scope.
Try to add $state.go($state.current, {}, {reload: true}) after changing $stateParams.

How to move controller source from app.js to desired folder location in angular project

I need help on moving controller from app.js to desired folder.
My Folder structure look likes the blw
---app
--home
--home.html
--homecontroller.js
--about
--contact
--app.html
--app.js
---asset
---index.html
I have kept my controller source in my app.js. But i planned to move the specific controller into the corresponding root folder. Lets say i have home controller code in app.js. Now i want to move it to homecontroller.js which placed in home folder. I tried that. but it doesn't work for me. However it works when i keep that in app.js.
Can you help me to move it to desired root.
my app.js is
var app = angular.module('TrailApp', ['ui.router'])
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home/part1');
$stateProvider
.state('base', {
abstract: true,
url: '',
templateUrl: 'app/app.html'
})
.state('home', {
url: '/home',
parent: 'base',
templateUrl: 'app/home/home.html',
controller: 'homectrl'
})
.state('home.part1', {
url: '/part1',
templateUrl: 'app/home/part1.html',
//controller: 'homectrl'
})
.state('home.part2', {
url: '/part2',
templateUrl: 'app/home/part2.html',
//controller: 'homectrl'
})
.state('about', {
url: '/about',
parent: 'base',
templateUrl: 'app/about/about.html',
//controller: 'aboutctrl'
})
});
//This below code should be moved to homecontroller.js
app.controller('homectrl', ['$scope', '$location', '$rootScope',
function($scope, $location, $rootScope) {
$scope.custom = false;
$scope.actionBtn = function(event) {
$scope.custom = true;
};
}
]);
You can get your answer here
In homecontroller.js
angular.module('TrailApp').controller('homectrl', ['$scope', '$location', '$rootScope',
function($scope, $location, $rootScope) {
$scope.custom = false;
$scope.actionBtn = function(event) {
$scope.custom = true;
};
}
]);
You have to inject that controller module in app.js. Like
var myApp=angular.module('myApp', ['controllers']);
This is your controller.js in other folder
var controllers = angular.module('controllers', []);

Ionic template does not work on mobile

I have been making an app in AngularJS with Angular-ui-router based on Ionic Framework. It works perfect on the desktop in every web browser, but it does not show anything on my mobile (after build I run it on 2 devices). The problem is that it doesn't load template inside ui-view.
I have got an index.html file, the body section is below (in head section there is everything included):
<body ng-app="starter">
<div ui-view=""></div>
</body>
And the part of app.js - run and config.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
.run(function($ionicPlatform, $rootScope, $location) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
history.back();
};
})
.config(function($stateProvider, $urlRouterProvider) {
"use strict";
$stateProvider
.state('connectionCheck', {
url: '/',
controller: ['$scope', '$location', '$http',
function($scope, $location, $http) {
$http.get('http://pingurl.com')
.success(function(data) {
jdata = data;
if (data.status === "success") {
$location.path('/login');
}else{
$location.path('/error');
}
})
.error(function() {
$location.path('/error');
});
$scope.retry = function() {
$location.path('/');
};
}
]
})
.state('login', {
url: '/login',
templateUrl: 'login.html'
})
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: ['$scope', '$location', '$localStorage',
function($scope, $location, $localStorage) {
$scope.username = $localStorage.username;
$scope.token = $localStorage.token;
$scope.email = $localStorage.email;
$scope.goToAlerts = function() {
$location.path('/alerts');
};
$scope.goToSettings = function() {
$location.path('/settings');
};
$scope.goToLocation = function() {
$location.path('/location');
};
$scope.goToSymptoms = function() {
$location.path('/symptoms');
};
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return "active"
} else {
return ""
}
};
}
]
})
.state('error', {
url: '/error',
templateUrl: 'error.html'
})
.state('register', {
url: '/register',
templateUrl: 'register.html',
})
.state('push', {
url: '/push',
templateUrl: 'push.html',
})
.state('alerts', {
url: '/alerts',
templateUrl: 'alerts.html'
})
.state('newSymptom', {
url: '/newSymptom',
templateUrl: 'newsymptom.html'
})
.state('symptoms', {
url: '/symptoms',
templateUrl: 'symptoms.html'
})
.state('newAlert', {
url: '/newalert',
templateUrl: 'newalert.html'
})
.state('settings', {
url: '/settings',
templateUrl: 'settings.html'
})
.state('location', {
url: '/location',
templateUrl: 'location.html'
});
$urlRouterProvider.otherwise('/');
}).
//some controllers goes here
What I have already checked/tried to do?
I put example content to index.html - it worked.
I tried chanage the name of ui-view and add them in templateURL values of each state.
I changed the .html files to exlude error in them, but it did not helped.
Can anyone more experienced with Ionic/Angular give me a hint what is wrong here?
I seem to notice that it's often due to the modules you're loading in. So It's likely in this line.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
Try checking each module by making sure:
You added it to your index.html
it's being called correctly
it's up to date
You can figure out by removing each, one at a time and then seeing if it works on the device.
Also know that AngularJS out of the box uses AngularUI Router and this uses a thing called routing for views. The UI-Router uses a thing called states that is the most used but the unofficial way for AngularJS and Ionic uses their own view state system that is basically the same thing as the UI-Router just with the Ionic namespace. So that is something you need to look up or you may find yourself running into a lot of walls during you builds because you are calling ui.router and I bet it's what's confusing your app, so remove it.

Angular: Passing params from $routeProvider to controller

I have multiple routes that invoke the same Controller and I would like to pass different variables to it.
// Example
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleB'
});
I know that I could use the "resolve" object:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
resolve: {test: function() { return true; }}
});
To pass a value as a dependency:
app.controller('MyController', ['$scope', 'test', function ($scope, test) {
console.log(test); // true
}
My problem with that approach is that my app crashes if the resolve object is missing on other routes and I would like to pass optional params.
Is there any way to pass specific params to the Controller (from the route provider)?
Thank you
Routing:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleB'
});
Access: inject $route in your controller then use this
app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
var paramValue = $route.current.$$route.paramExample;
console.log(paramValue);
}
You can use resolve and $route.currrent.params.test to pass the parameter like this:
$routeProvider
.when('/a', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = true; }
}
})
.when('/b', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = false; }
}
})
Then in your controller you can access it from the $routeParams:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.test = $routeParams.test;
})
http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview
The most natural way to do this is doing what you would normally do when you want to load a page with parameters: use query parameters: http://yoururl.com?param1=value&param2=value
ngRoute comes with the service $routeParams which you can inject in your controller. Now you can simply retrieve the values like this $routeParams.param1.
Another way to do this is to retrieve the path with $location.path and set the variable there.
using $routeParams
in Main js file
routeApp.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '../sites/./home.html',
controller: 'StudentController'
})
.when('/viewStudents/:param1/:param2', {
templateUrl: '../sites/./viewStudents.html',
controller: 'StudentController'
})
.otherwise({
redirectTo: '/'
});
});
routeApp.controller('StudentController',['$filter','$routeParams', '$location',function($filter,$routeParams,$location){
var StudentCtrl = this;
StudentCtrl.param1 = $routeParams.param1;
StudentCtrl.param2 = $routeParams.param2;
}]);
calling from Home.html
<div class="container">
<h2> Welcome </h2>
Students
</div>

$routeParams Empty on $locationChangeSuccess

I configure my app in the following run block. Basically I want to preform an action that requires me to know the $routeParams every $locationChangeSuccess.
However $routeParams is empty at this point! Are there any work rounds? What's going on?
app.run(['$routeParams', function ($routeParams) {
$rootScope.$on("$locationChangeSuccess", function () {
console.log($routeParams);
});
}]);
UPDATE
function configureApp(app, user) {
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/rentroll', {
templateUrl: 'rent-roll/rent-roll.html',
controller: 'pwRentRollCtrl'
}).
when('/bill', {
templateUrl: 'bill/bill/bill.html',
controller: 'pwBillCtrl'
}).
when('/fileroom', {
templateUrl: 'file-room/file-room/file-room.html',
controller: 'pwFileRoomCtrl'
}).
when('/estate-creator', {
templateUrl: 'estate/creator.html'
}).
when('/estate-manager', {
templateUrl: 'estate/manager.html',
controller: 'pwEstateManagerCtrl'
}).
when('/welcomepage', {
templateURL: 'welcome-page/welcome-page.html',
controller: 'welcomePageCtrl'
}).
otherwise({
redirectTo: '/welcomepage'
});
}]);
app.run(['$rootScope', '$routeParams', 'pwCurrentEstate','pwToolbar', function ($rootScope, $routeParams, pwCurrentEstate, pwToolbar) {
$rootScope.user = user;
$rootScope.$on("$locationChangeSuccess", function () {
pwToolbar.reset();
console.log($routeParams);
});
}]);
}
Accessing URL:
http://localhost:8080/landlord/#/rentroll?landlord-account-id=ahlwcm9wZXJ0eS1tYW5hZ2VtZW50LXN1aXRlchwLEg9MYW5kbG9yZEFjY291bnQYgICAgICAgAoM&billing-month=2014-06
this worked for me, inside your run callback:
.run(function($rootScope, $routeParams, $location) {
$rootScope.$on("$locationChangeSuccess", function() {
var params = $location.search();
console.log(params);
console.log('landlord-account-id:', params['landlord-account-id']);
console.log('billing-month', params['billing-month']);
});
})
By accessing /rentroll you will get empty $routeParams because your $routeProvider
configuration for that path is not expecting any variable on URL.
$routeParams is used for getting variable value of your URL. For example :
$routeProvider
.when('/rentroll/:variable', {...});
and access it on /rentroll/something will give you $routeParams as below :
$routeParams.variable == 'something';
https://docs.angularjs.org/api/ngRoute/service/$routeParams
Explains a bit about when the $routeParams are available and why.
To solution here might be to use $route.current.params

Categories