Angular - $stateParams Is Empty In Controller - javascript

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.

Related

Passing paramter to URL using ui-router

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)
}])

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.

Angular $routeParams: get query parameter as array

When I have multiple id parameters in query, $routeParams.id gives me an array.
That's great. But, if only one id is present in the query, I get a string.
/?id=12&id=34&id=56 // $routeParams.id = ["12", "34", "56"]
/?id=12 // $routeParams.id = "12"
This is bad. Because in the first case, $routeParams.id[0] gives "12",
while in the second one, it gives "1" (first char of "12").
I can work this around by inserting an empty id= to all my links, but this is ugly.
See in Plunker
Is "type-checking in controller" my only option? If so, how do I do it?
index.html:
<html ng-app="app">
<head>
<script src="//code.angularjs.org/1.3.15/angular.js"></script>
<script src="//code.angularjs.org/1.3.15/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
home.html:
#/?id=12<br/>
#/?id=12&id=34&id=56<br/>
#/?id=12&id=<br/>
<pre>id: {{id | json:0}}</pre>
<pre>id[0]: {{id[0] | json}}</pre>
script.js:
angular.module('app', ['ngRoute'])
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}
])
.controller('HomeCtrl', [
'$scope', '$routeParams',
function($scope, $routeParams) {
$scope.id = $routeParams.id;
}
]);
EDIT:
For those who wonder, what I am trying to achive is: inter-controller (or inter-view) communication. User selects some items in one view, and sees details for those selected items in the next view. See in Plunker.
The best way to do it is not to use id param multiple times but separate your values with another character and always get an array and you are ready to go!
script.js
(function() {
var app = angular.module('app', ['ngRoute']);
app.config([
'$routeProvider',
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}
]);
app.controller('HomeCtrl', [
'$scope', '$routeParams',
function($scope, $routeParams) {
$scope.id = $routeParams.id.split('-');
}
]);
})();
home.html
<p>
#/?id=12-34-56 Array
</p>
<p>
#/?id=12 Array
</p>
<pre>id: {{id | json:0}}</pre>
<pre>id[0]: {{id[0] | json}}</pre>
I wonder why you are passing different values to a single id. However, this should solve your problem
angular.module('app', ['ngRoute'])
.config([
'$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}
])
.controller('HomeCtrl', [
'$scope', '$routeParams', function($scope, $routeParams) {
$scope.id = angular.fromJson($routeParams.id);
}
]);

How to set ng-show on a specific element through different views/controllers?

Plunker: http://plnkr.co/edit/0efF1Av4lhZFGamxKzaO?p=preview
Below is my header, there is an ng-show="cornerLogo" which I only want to be set true on the about, login and register views, but false the home view.
<body id="body_id"
ng-app="myApp"
ng-controller="HomeCtrl">
<header>
<section ng-show="cornerLogo">
<h1>Logo</h1>
</section>
<nav id="main_nav">
<ul>
<li><a ui-sref="about">About</a></li>
<li><a ui-sref="login">Sign In</a></li>
<li><a ui-sref="register">Create Account</a></li>
</ul>
</nav>
</header>
<ui-view></ui-view>
So it works in my HomeCtrl because that is the main controller on the page.
var app = angular.module('app-home', [])
.controller('HomeCtrl', ['$scope', function($scope) {
$scope.cornerLogo = false;
}]);
However when I switch to the about, login or register views I lose that $scope
Is there a way somehow to have a global var set somewhere in my stateProvider for ui-router? Otherwise, how would you go about this issue?
var app = angular.module('bitAge',
['ui.router',
'app-header',
'app-home',
'app-about',
'app-login',
'app-register'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '_views/home.html',
controller: 'HomeCtrl',
})
.state('about', {
url: '/about',
templateUrl: '_views/about.html',
controller: 'AboutCtrl'
})
.state('login', {
url: '/login',
templateUrl: '_views/login.html',
controller: 'LoginCtrl'
})
.state('register', {
url: '/register',
templateUrl: '_views/register.html',
controller: 'RegisterCtrl'
});
// default view:
$urlRouterProvider.otherwise('/home');
}]);
Apart from my comments in the question, to fix your issue you can take this approach.
You have HomeCtrl specified as bound controller in the state registration of home partial. So instead create a main controller for your application. So that you keep the responsibilities separated out. Inject $state and expose a method called hideLogo and use $state.is to determine the logic to show/hide the logo.
i.e:
var app = angular.module('app-home')
.controller('MainCtrl', ['$scope', '$state', function($scope, $state) {
$scope.hideLogo = function(){
return $state.is('home');
}
}]);
In the index html use MainCtrl as your main controller for the app.
<body ng-app="myApp" ng-controller="MainCtrl">
<header>
<section
ng-hide="hideLogo()">
<h1>Corner Logo</h1>
</section>
Plnkr
If you want to use $state directly on the view you would need to inject it in MainCtrland set $state on the $scope object so that you can use it directly. Though i highly recommend not to use this technique, you should not expose state in the scope object and ultimately in the view. Just expose only what is needed in the viewmodel.
i.e in the MainCtrl :
var app = angular.module('app-home')
.controller('MainCtrl', ['$scope', '$state', function($scope, $state) {
$scope.$state= $state;
}]);
and just use it on the view as:
<section
ng-hide="$state.is('home')">
You can check your current state and depends on that, show or not your logo.
<section ng-show="$state.includes('home')">
<h1>Logo</h1>
</section>
Also, your anchor elements to navigate, should be like this <a ui-sref="about">About</a> and so on, because if you use normal href attribute, angular wont change state.
Also, you need to inject $state in your main module and then you can use $state module
var app = angular.module('myApp',
['ui.router',
'app-home',
'app-about']).run(function ($state,$rootScope) {
$rootScope.$state = $state;
})
UPDATE:
Here is the punklr with the answer

Angular Controllers Firing off more than once. Only certain ones

I have markup that has the following and then I have different sections of the app defined in different files. The problem I am running into is that the controllers that are on the main app page on load causes each of the nested controllers to run more than once. Any states that I change to with a click of the button are fine but these fire off 2-3 times each.
<html ng-app="myApp">
<body ng-controller="myController">
<div ng-controller="dashController">
<div ng-controller="listController">
</div>
</div>
</body>
</html>
My App.js
var myApp = angular.module('myApp', [
'user.profile',
'myApp.controllers',
'myApp.directives',
'ngCookies',
'ngAutocomplete',
'ui.router'
]).config(function($stateProvider, $urlRouterProvider, $locationProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$urlRouterProvider.otherwise('/');
$stateProvider.
state('app', {
url: '/app',
templateUrl: '/views/homepage',
controller: 'MyCtrl1'
});
$locationProvider.html5Mode(true);
});
myApp.controllers
angular.module('myApp.controllers', ['ui.router','ngCookies']).
controller('myController', function ($scope, $http,$cookies) {
$scope.message = 'nothing to see here, move along';
if ($cookies.userdata) {
$cookies.userdata = $cookies.userdata.replace("j:", "");
console.log($cookies);
}
});
user.profile.js
angular.module('user.profile', [
'user.controllers',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'nouislider',
'ui.router',
'ui.bootstrap',
'ngLinkedIn'
])
.config(function($stateProvider, $urlRouterProvider, $locationProvider,$interpolateProvider, $linkedInProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$linkedInProvider.set('appKey', '753pos06f998t3')
.set('scope', 'r_fullprofile');
//.set('authorize', true);
$locationProvider.html5Mode(true);
$stateProvider
.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
});
user.controllers.js
angular.module('user.controllers', ['ui.router', 'ngAutocomplete', 'nouislider', 'ui.bootstrap', 'ngCookies', 'ngLinkedIn', 'angularFileUpload','cgPrompt'])
.directive('onLastRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
}).
controller('dashController', function ($scope, $state, $modal, $log, $http, $cookies) {
$scope.user = [];
}).
controller('listController', function ($scope, $http, $cookies) {
});
My app also doesn't initialize unless I run angular.bootstrap(document, ["myApp"]);
I don't think it is having the controller defined in the $stateProvider and the DOM... if I remove from the DOM none of the ng-clicks work even after the controller fires... also I have an ng-click that changes the state and it's controller is defined in the stateProvider and in the DOM and it does not fire twice... what is does is kick off the two other controllers again first before proceeding with it's action though.
The issue is that you are defining your controllers with the routeProvider / stateProvider ie:
$stateProvider.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
an you are redifining them in the DOM using
<div ng-controller="dashController">
remove one or the other but don't use the two at the same time, I'd suggest to remove the one declared in the DOM, ng-controller="dashController"
cheers

Categories