Passing paramter to URL using ui-router - javascript

I keep seeing examples on this but I don't know what I am doing wrong.
I load an item and its content into ng-view. When I refresh the page, it disappears. I have passed a parameter to the URL of the state and I am lost what to do next.
People have talked about $stateParams which I can log from my controller and I can see that item with id: 3 has been selected.
How do I keep the view populated with this item even on refresh? An example with my code would be greatly appreciated.
var app = angular.module('myApp', ['ngRoute', 'ui.router']);
app.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', '$routeProvider', function($stateProvider, $locationProvider, $urlRouterProvider, $routeProvider) {
$urlRouterProvider
.otherwise('/patents');
$stateProvider
.state("patents", {
url: "/patents",
templateUrl: "templates/patents/list/list-patents.htm",
controller: "patentListCtrl",
})
.state("patents.item", {
url: "/:id",
templateUrl: function() {
//THIS IS WHERE I AM NOT SURE HOW TO PASS THE URL THE ID
},
controller: "patentItemCtrl"
})
}]);
app.controller('patentItemCtrl', ['$scope', 'patentTabService','$stateParams', '$state', '$routeParams', function($scope, patentTabFactory, $stateParams, $routeParams){
console.log($stateParams.id)
}])

You should be able to to retrieve the required data by making a call your data service and then assign to your view. In your case call patentTabService to get patent with the id and then load that patent object into your view. For example, note I am assuming you already have some way to get a patent by id in your service:
app.controller('patentItemCtrl', ['$scope', 'patentTabService','$stateParams', '$state', '$routeParams', function($scope, patentTabFactory, $stateParams, $routeParams){
$scope.patent = {};
if (Number.isInteger($stateParams.id) ){
$scope.patent = patentTabFactory.getPatent($stateParams.id);
}
console.log($stateParams.id)
}])

Related

Angular $routeParams empty object

I'm trying to get a query value from my url using angular's routeParams.
I've included angular-route in my html page:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>
Included Ng-Route in my app:
var app = angular.module('app', [
'ngRoute',
'reportController'
]);
And set up my controller as following:
var reportController = angular.module('reportController', []);
reportController.controller('CandidateCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
console.log(JSON.stringify($routeParams, null, 4));
$scope.person = $routeParams.person;
}]);
When I access the following URL, however, routeParams is an empty object: {}.
http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad
What am I doing wrong?
Edit:
I've configure the possible route - my routeParams object is still coming up null. I've tried:
famaApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/report:person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
}]);
and
when('/report?person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
Rather then accessing like
http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad
try to access it like
http://localhost:8080/#/report/afe75cc7-fa61-41b3-871d-119691cbe5ad
you will get the guid in $route.Params
You have to set your routes to receive the arguments you want with $routeProvider..
Example:
app.config(['$routeProvider', '$locationProvider' function ($routeProvider, $locationProvider) {
$routeProvider
.when('/',
{
templateUrl: 'someHtmlUrl',
controller: 'someController',
controllerAs: 'someCtrl',
caseInsensitiveMatch: true
})
.when('/:person',
{
templateUrl: 'someHtmlUrl',
controller: 'someController',
controllerAs: 'someCtrl',
caseInsensitiveMatch: true
})
.otherwise(
{
templateUrl: 'someHtmlUrl'
});
$locationProvider.html5Mode(true); //Use html5Mode so your angular routes don't have #/route
}]);
Then you can just do
http://localhost:8080/afe75cc7-fa61-41b3-871d-119691cbe5a
And the $routeProvider will call your html and your controller as you can see with the .when('/:person'.. and then you can try and access your $routeParams and you will have your person there, $routeParams.person.

$location is not working in Angular

I have an rest api, in which the api is sending instruction to redirect (301 is being sent).
And I have my angular js code like this:
var request = $http.post(LOGIN_URL,{username:'tes',password:'test'})
request.success(function(html)
{
if(html.failure) {
console.log("failure")
$scope.errorMessage = html.failure.message
}
else {
console.log("Success here....")
$location.path("route")
}
})
I can see in the browser log that it is coming in the else part ( Success here..... is being printed). But the url is not changed. $location.path doesnt do anything; I have also tried $location.url which also results the same thing.
And also I'm injecting the $location to my controller.
Where I'm making mistake?
Thanks in advance.
Try something like this
$location.path("/myroute")
You have to have a ng-view on the page as well.
Also make sure you have a corresponding view with that name
and when you're registering your controller you have the '$location' var being injected in the declaration of your controller like this example:
controllers.controller('MyCtrl', ['$scope', '$route', '$location', 'MYService',
function($scope, $route, $location, MyService) {
// ... controller code
}])
also you might want to debug your route changing to see what is happening with a location change listener, like in this example:
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'MyCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/error/:errorId', {
templateUrl: 'partials/error.html',
controller: 'ErrorCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]).run(function($rootScope, $injector, $location) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
console.log('current=' + current.toString());
console.log('next=' + next.toString());
});
});
});

Getting URL parameters using $route

I have the following url:
http://myurl.dev/users/32
I want to pass the last parameter 32 to a $http.get request but I can't figure out how to pass it.
So far I have this:
var matchmaker = angular.module('matchmaker', ['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.controller('LocationCtrl', ['$scope', '$http', '$location', '$routeParams', '$route', function($scope, $http, $location, $routeParams, $route) {
var id = $route.current.params.id;
console.log(id);
$http.get('http://myurl.dev/services/' + id ).success(function(data)
{
$scope.applicants = data;
});
}]);
In the console it's saying:
Cannot read property 'params' of undefined
Can anyone tell me what I'm doing wrong please?
Edit:
Angular isn't generating the url, it's a server side generated url
Edit 2.0
Here's the config for the routeProvider with actual route parameters:
var matchmaker = angular.module('matchmaker', ['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/matchmaker/locations/:id', {
controller: 'LocationCtrl'
});
$locationProvider.html5Mode(true);
});
Put a console.log($routeParams); in your controller and check its value.
If it is Object {} check if you have a route definition using parameters:
var module = angular.module('ngRouteExample', ['ngRoute']);
module.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/test/:id', {
templateUrl: 'test.html',
controller: 'TestController'
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
If so, you will get this output in the console:
Object {id: "42"}
It is because you trying to get value which doesn't exist at that moment, that's how javascript works. You need to specify that you want these values when they are ready using '$routeChangeSuccess' event.
.controller('PagesCtrl', function ($rootScope, $scope, $routeParams, $route) {
//If you want to use URL attributes before the website is loaded
$rootScope.$on('$routeChangeSuccess', function () {
//You can use your url params here
$http.get('http://myurl.dev/services/' + $routeParams.id )
.success(function(data) {
$scope.applicants = data;
});
});
});

Angular - $stateParams Is Empty In Controller

I am having a lot of trouble understanding how stateParams are supposed to work. Everywhere I look suggests that this should pass an item_id of 456 when I travel to the URL /#/manage/456, but instead $stateParams is an empty object. Furthermore, in the $state object that is passed to MainCtrl, I can access all of the parameters by using $state.params, however this seems to be undesirable and hackish.
angular
.module('router',['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)
{
$stateProvider
.state('manage',
{
url: '/manage',
templateUrl: '/templates/main.html',
controller: 'MainCtrl'
})
.state('manage.item_id',
{
url: '/:item_id',
templateUrl: '/templates/main.html',
controller: 'MainCtrl'
})
}])
.controller('MainCtrl', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state)
{
// empty object
console.log('$stateParams: ', $stateParams);
// shows the variables i want
console.log('$state.params: ', $state.params);
}])
What you're trying to do should work fine, see this JSFiddle: http://jsfiddle.net/ahchurch/gf7Fa/14/
<script type="text/ng-template" id="item.tpl.html">
embeded item template
</script>
<script type="text/ng-template" id="main.tpl.html">
<ul>
<li>change route</li>
</ul>
<div ui-view></div>
</script>
<div ui-view></div>
angular.module('myApp',['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise("/manage");
$stateProvider
.state('manage',
{
url: '/manage',
templateUrl: 'main.tpl.html',
controller: 'MainCtrl'
})
.state('manage.item_id',
{
url: '/:item_id',
templateUrl:'item.tpl.html',
controller: 'MainCtrl'
})
}])
.controller('mainController', function(){})
.controller('MainCtrl', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state)
{
// empty object
console.log("main controller");
console.log($stateParams);
}]);
One thing I noticed is that your template is the same file for both states, so you may just be seeing the initialization of the "manage" state, and never seeing the "manage.item_id" state.

Using Angular services to hold commonly required data

I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])

Categories