angularjs state parameters not working - angularjs

I'm having an issue trying to pass a parameter object to a state using stage.go().
Here is my state definition:
.state('drillhole.ddhinttype', {
url: '/ddhinttype',
templateUrl: VIRTUAL_DIR_PATH + '/App/Views/drillholemanager/drillhole/tabddhinttype.html?v=' + fileVer,
controller: 'DrillHoleDdhIntTypeController',
params: { name: null, description: null }
})
And here is my controller:
try {
angular.module('centric.drillhole.manager');
} catch (e) {
angular.module('centric.drillhole.manager', ['app.config', 'ui.router', 'kendo.directives', 'ui.bootstrap', 'ngCookies', 'centric.common', 'centric.notification', 'pascalprecht.translate', 'centric.security', 'centric.app.settings']);
}
angular.module('centric.drillhole.manager').controller('DrillHoleDdhIntTypeController', ['$scope', 'CentricUIHelper', 'NumberHelper', 'DrillHoleManagerService', 'app.config', '$stateParams',
function ($scope, uihelper, numberHelper, service, appconfig, $stateParams) {
$scope.loading = false;
$scope.isbusy = function () {
return $scope.loading || $scope.$parent.loading;
}
var load = function () {
var hello = $stateParams.name;
var hello2 = $stateParams.description;
};
load();
}]);
And I'm calling the state like so:
$state.go('drillhole.ddhinttype', { name: tab.params.name, description: tab.params.description });
In my controller the name and description properties are always null.
Not sure what I'm missing here. Any ideas?

If you put the params in your url you will be able to access it in controller using $stateParams
.state('drillhole.ddhinttype', {
url: '/ddhinttype/:name/:description',
templateUrl: VIRTUAL_DIR_PATH + '/App/Views/drillholemanager/drillhole/tabddhinttype.html?v=' + fileVer,
controller: 'DrillHoleDdhIntTypeController',
params: { name: null, description: null }
})
You can read more about url routing here: https://github.com/angular-ui/ui-router/wiki/url-routing

Try this in the state definition:
params: { name: undefined, description: undefined }
or this:
params: ['name', 'description']

I feel like I should post the final result. I have decided to pass the parameter in the URL so that I can re-use the same controller for several tabs which each have the same functionality but against different tables in the DB.
Here is the part of my base controller which creates the tabs (CoreLogController.js):
service.getDrillHoleIntervalTypes()
.success(function (res) {
$scope.data.drillHoleIntervalTypes = res;
for (var i = 0; i < $scope.data.drillHoleIntervalTypes.length; i++) {
// add the tab and set it as active if we're in the correct $state
$scope.dynamictabs.push({ heading: $scope.data.drillHoleIntervalTypes[i].Name, route: 'drillhole.ddhinttype', params: { ddhinttype: $scope.data.drillHoleIntervalTypes[i].Name }, active: ($scope.$state.params.ddhinttype == $scope.data.drillHoleIntervalTypes[i].Name) });
}
})
.error(function (error) {
uihelper.showError(error);
});
And here is the relevant HTML portion where the tabs are shown (corelog.html):
<tabset>
<tab ng-repeat="t in statictabs" heading="{{t.heading}}" ui-sref="{{t.route}}" active="t.active"></tab>
<tab ng-repeat="t in dynamictabs" heading="{{t.heading}}" ui-sref="drillhole.ddhinttype({ddhinttype: '{{t.params.ddhinttype}}'})" active="t.active"></tab>
</tabset>
And here is where I define the state (app.js):
.state('drillhole.ddhinttype', {
url: '/ddhinttype/{ddhinttype}',
templateUrl: VIRTUAL_DIR_PATH + '/App/Views/drillholemanager/drillhole/tabddhinttype.html?v=' + fileVer,
controller: 'DrillHoleDdhIntTypeController',
params: { ddhinttype: null }
})
I now get access to the ddhinttype variable on each instance of the controller (DrillHoleDdhIntTypeController.js) which tells it which table to perform operations against.
Since ddhinttype is also contained the URL the user can create a bookmark which will bring them right back to the same tab even though they are dynamically generated.

Related

Unable to transition to state, getting error that state is not defined

I am currently on the main page after invoking
http://localhost:8199/#/iceberg-ui
I have a state called iceberg.reconcreate as defined below.
But when I try to invoke $state.go('iceberg.reconcreate') on the click of a button, I get the error that state is not defined.
angular-ui-router.js:982 Uncaught Error: No such state undefined at
Object.transitionTo (angular-ui-router.js:982) at Object.go
(angular-ui-router.js:973) at HTMLAnchorElement.
(angular-ui-router.js:1383) at HTMLAnchorElement.dispatch
(jquery.js:4641) at HTMLAnchorElement.elemData.handle (jquery.js:4309)
ROUTING
routingSetup.$inject = ['$stateProvider', '$urlRouterProvider'];
function routingSetup($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/iceberg-ui");
$stateProvider
.state('iceberg', {
url: "/iceberg-ui",
templateUrl: "app/iceberg/iceberg.view.html",
controller: 'IcebergController as icebergCtrl'
})
.state('iceberg.reconlist', {
templateUrl: "app/iceberg/recon/list/recon.list.view.html",
controller: 'ReconListController as reconListCtrl'
})
.state('iceberg.reconcreate', {
templateUrl: "app/iceberg/recon/create/recon.create.view.html",
controller: 'ReconCreateController as reconCreateCtrl'
})
.state('iceberg.recondetails', {
templateUrl: "app/iceberg/recon/details/recon.details.view.html",
controller: 'ReconDetailsController as reconDetailsCtrl'
})
}
Controller
(function() {
'use strict';
var myApp = angular.module('iceberg.recon');
myApp.controller('ReconListController', ReconListController);
ReconListController.$inject = ['ReconListService', '$state'];
function ReconListController(ReconListService, $state) {
var vm = this;
function getReconciliationList() {
return {
load: function(loadOptions) {
var reconList = ReconListService.getReconciliationList();
return {
data: reconList,
totalCount: reconList.length
};
},
update: function(key, values) {
console.log("calling the UPDATE GRID");
//Do Nothing, this method is required else the framework throws an error
}
};
}
vm.createNewRecon = {
text: "Create New Reconciliation",
icon: "plus",
type: "success",
height: "45px",
onClick: function(e) {
$state.go('iceberg.reconcreate');
}
};
}
}());
UPDATE - Updated with controller details
Sorry folks, that was an oversight from my end. I had a ui-sref defined with the incorrect name and all this while I was thinking it was getting called as a onclick event. My bad, apologies for the same.

Angularjs - read inside json file

This is my first attempt with angularjs and ionic-framework.
I have an example json file and i'd like to display onscreen some data from it.
The displaying-data bit works, but i'd like to populate a "details" page with some info that are stored as an abject inside the main json file, and i need to use the id from the url to select to display only the data that i need.
Here's some code:
App.js
angular.module('hgapp', ['ionic', 'hgapp.controllers', 'ngResource'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.details', {
url: '/details/:roomID',
views: {
'menuContent': {
templateUrl: 'templates/details.html',
controller: 'DetailsCtrl'
}
}
})
$urlRouterProvider.otherwise('/app/home');
});
Controllers.js
angular.module('hgapp.controllers', ['hgapp.services'])
.controller('AppCtrl', function ($scope, HGJson) {
HGJson.get(function (data) {
$scope.rooms = data.data;
})
})
.controller('DetailsCtrl', function ($scope, $stateParams, HGJson) {
$scope.roomID = $stateParams.roomID;
console.log($stateParams.roomID);
})
services.js
angular.module('hgapp.services', ['ngResource'])
.factory('HGJson', function ($resource) {
return $resource('json/data.json')
});
Data.json (Just a simplified example)
{
tm: 00000000,
errors: 0,
data: {
{id: 0, name: Value 0, url:url-0},
{id: 1, name: Value 1, url:url-1},
{id: 2, name: Value 2, url:url-2}
}
details.html
<ion-view view-title="Details">
<ion-content>
<h1>{{roomID}}</h1>
</ion-content>
In the details page i'm printing the roomID just to see if the controller (detailsCtrl) works, and i have the correct id printed every time. Now, the bit where i'm stuck is how to manipulate the data from HGJson service so that it allows my to print on data from the right room id.
I hope this question is clear enought, if not, feel free to ask for more clarification.
Thanks a lot
EDIT
At the end i solved it adding this to my controller.js file:
.controller('DetailsCtrl', function ($scope, $stateParams, HGJson) {
HGJson.get(function (data) {
angular.forEach(data.data, function (item) {
if (item.id == $stateParams.roomID)
$scope.currentRoom = item;
});
});
})
Just do the same thing as what you're doing in the app controller, but find the room you want in the returned JSON:
HGJson.get(function (data) {
$scope.room = data.data.filter(function(room) {
return room.id == $stateParams.roomID);
})[0];
});
You could also put that filtering functionality in your service, so that in the future, when you have a real dynamic backend, you call a different URL returning only the requested room rather than calling a URL that returns all the rooms.
angular.module('hgapp.services')
.factory('HGJson', function ($http) {
return {
getRooms: function() {
return $http.get('json/data.json').then(function(response) {
return response.data;
});
},
getRoom: function(roomId) {
return $http.get('json/data.json').then(function(response) {
return response.data.data.filter(function(room) {
return room.id == roomID;
})[0];
});
}
};
});
Note that your JSON is invalid: data must be an array, not an object.
In your controller, you will need to create a function to "find" the correct object in your data object.
Try something like this:
$scope.getRoom = function(id) {
for(var i in $scope.rooms) {
if($scope.rooms[i].id === id) {
return $scope.rooms[i];
}
}
};
And you can display it in your DOM:
{{ getRoom(roomID) }}
BUT it would probably be even better to set the current room to a scoped variable instead of running the function every time. So in this case (I strongly recommend), instead of returning $scope.rooms[i], you could set angular.copy($scope.rooms[i], $scope.currentRoom) (this will copy the room into the currentRoom scoped variable) and then use it in the DOM with simply {{ currentRoom }}
Good luck!

Firebase child_added and ng-repeat

I used child_added and ng-repeat to display a list of statuses, this part worked fine, but when I click on one of the statuses in the list i am sent to tab/statuses/ instead of going to tab/statuses/:statusid. Any help would be much appreciated.
app.js
.state('tab.statuses', {
url: "/statuses",
views: {
'tab-statuses': {
templateUrl: "templates/statuses.html",
controller: "StatusesController"
}
}
})
.state('tab.status', {
url: "/statuses/:statusid",
views: {
'tab-statuses': {
templateUrl: "templates/status.html",
controller: 'StatusController'
}
}
})
statusescontroller
app.controller('StatusesController', function ($scope, $filter, $state, $ionicListDelegate, $ionicActionSheet, StatusesService) {
$scope.statuses = [];
var ref = new Firebase("https://app85.firebaseio.com/statuses");
ref.on("child_added", function(snapshot, prevChildKey) {
var status = snapshot.val();
$scope.statuses.push(status);
});
})
statuses.html
<ion-item ng-repeat="status in statuses" href="#/tab/statuses/{{status.$id}}" class="customItemSize mlSmallerFont item-icon-left item-icon-right">
<i class="icon ion-ios-person-outline"></i>
{{ status.update }}
</ion-item>
You seem to be borrowing some ideas from AngularFire, but don't have the code to implement them. As it currently is the {{status.$id}} in your HTML has no value.
To fix that you should either use AngularFire or populate a $id in your controller:
ref.on("child_added", function(snapshot, prevChildKey) {
var status = snapshot.val();
status['$id'] = snapshot.key();
$scope.statuses.push(status);
});
Note that this will only work when snapshot.val() is an object (so not when it's a primitive). But since that is the case in your snippet, this should work.

passing form data from one controller to another in angular

.controller('CyclesController', function ($scope, $state) {
$scope.age = 0;
$scope.name = "";
$scope.email = "";
$scope.calculateByAge = function (age, name, email) {
$scope.data = $scope.data || {};
if (age > 0) {
$scope.data.age = age;
$scope.data.name = name;
$scope.data.email = email;
$state.go('tab.cycles-detail');
}
}
})
.controller('CyclesDetailController', function ($scope, $stateParams, CyclesService) {
console.log('scope data', $scope.data); // <--- undefined.
})
This may be a dumb question, but can get to get the data from the form on the CyclesDetailController controller.
If it's simple property you could do it by routing. Just change your "tab.cycles-detai' to 'tab.cycles-detai/:age' in your ui-router configuration and pass it when you're redirecting: $state.go('tab.cycles-detail', {age: age});
in 'CyclesDetailController' access it by $stateParams.age;
e.g:
//app.config
//...
.state('tab.cycles-detail', {
url: "^detail/{age:int}",
controller: 'CyclesDetailController',
templateUrl: "url_for_detail_template"
})
//...
// CyclesController
.controller('CyclesController', function ($scope, $state) {
$scope.age = 0;
$scope.calculateByAge = function (age) {
$scope.data = $scope.data || {};
if (age > 0) {
$scope.data.age = age;
$state.go('tab.cycles-detail', {age: age);
}
}
})
//CyclesDetailController
.controller('CyclesDetailController', function ($scope, $stateParams, CyclesService) {
console.log('scope data', $stateParams.age);
})
//
If you want to pass data from one route to another but dont want to expose it in browser menu bar, you can use squash.
Example -
.state('app.enroll', {
url: '/enroll/',
params: {
classId: {
value: null,
squash: true
},
className: {
value: null,
squash: true
}
},
title: 'Students Enrollment',
templateUrl: helper.basepath('enroll.html')
})
2nd Technique -
You can use localStorage / cookies to save data and retrieve at later stage.
3rd Technique -
You can always share data via services/factory in between controllers.

Pass object as parameter in $state.go

I want to navigate to another state/screen and pass a simple json object to this next screen.
I have the following:
var benefit = { "x": "y"};
$state.go('pages.claimed', { 'benefit': benefit });
My state looks like this:
.state('pages.claimed', {
url: '/claimed',
views: {
'page': {
templateUrl: 'templates/pages/claimed.html'
}
}
})
I can't however access the "benefit" object/parameter in the pages.claimed view. I'm using the ionic framework based on angular.
Parse object to json:
var benefit = angular.toJson({ "x": "y"});
Define variable in state params:
.state('pages.claimed', {
url: '/claimed?params',
views: {
'page': {
templateUrl: 'templates/pages/claimed.html'
}
}
})
Access to variable from controller via $stateParams:
var benefit = angular.fromJson($stateParams.benefit);
Here full doc
Edit:
There are several ways to pass an object to controller from url:
Via query params:
define options url: '/yoururl?a&b&c',
pass variables yoururl?a=1&b=2&c=3
Via url params:
define options url: '/yoururl/:a/:b/:c',
pass variables yoururl/1/2/3
For more complicated situations you can parse your object to json string and encode it with base64
Object: { a:1, b:2, c:3 }
JSON String: {"a":1,"b":2,"c":3}
Base64 Encoded string: eyJhIjoxLCJiIjoyLCJjIjozfQ==
define options url: '/yoururl?params'
pass variables yoururl?params=eyJhIjoxLCJiIjoyLCJjIjozfQ==
More info about base64
$state.go should be corrected like this
var benefit = { "x": "y"};
$state.go('pages.claimed', { benefit: benefit });
.state should be like this
.state('pages.claimed', {
url: '/claimed',
params: { benefit: null },
views: {
'page': {
templateUrl: 'templates/pages/claimed.html'
}
}
})
Catch the passed object as follows in the next controller
(function () {
'use strict';
angular.module('YourAppName').controller('ControllerName', ['$stateParams', ControllerName]);
function ControllerName($stateParams) {
var vm = this;
vm.variableToBind = $stateParams.benefit;
};
})();
Very clean solution:
app.js:
$stateProvider.state('users', {
url: '/users',
controller: 'UsersCtrl',
params: { obj: null }
})
controllers.js
function UserCtrl($stateParams) {
console.log($stateParams);
}
Then from any other controller:
$state.go('users', {obj:yourObj});
I'm not sure what you're application is doing, but if you need to share information between two controllers you should be using some sort of service, not passing a bunch of data through the URL. The URL is to pass parameters around to identify the state, not be the means of data transportation.
You're probably going to want a factory of some sort. Here's a little benefit registration service... assuming underscore.
.factory('benefitsService', ['_', function(_){
function BenefitsService(){
this.benefits = [{
id: 'benefit1',
x: 100,
y: 200
},{
id: 'benefit2',
x: 200,
y: 300
}];
}
// use this to register new benefits from a controller, other factory, wherever.
BenefitsService.prototype.addBenefit = function(benefit){
this.benefits.push(benefits);
}
BenefitsService.prototype.findById = function(id){
return _.findWhere(this.benefits, {id: id});
}
return new BenefitsService();
}]);
.run(['benefitsService', function(benefitsService){
// we're going to register another benefit here to show usage....
benefitsService.addBenefit({
id: 'addedBenefit',
x: 2000,
y: 4000
});
}])
Then you just pass the id through the URL to something normal "/url/:id"
.controller('firstController', ['$state', function($state){
$state.go('stateId', {
id: 'addedBenefit'
});
});
// and use your injected service to find your data.
.controller('secondController', ['$state', 'benefitService', function($state, benefitService){
var benefit = benefitService.findById($state.params.id);
// and you're home!
}]);
This way you don't end up with a bunch of cruft inside of your URL, only what you need to identify state. You've also obfuscated the storage mechanism, so you can use an object, local storage, or any synchronous storage mechanism you'd like.
You also have a service you can inject and use anywhere else through your application.
Looks like you missed parameter 'data' in your state:
.state('pages.claimed', {
url: '/claimed',
views: {
'page': {
templateUrl: 'templates/pages/claimed.html'
}
},
data: {
benefit: {}
}
})
Here is description from documentation

Resources