Params with $state.go and $scope - javascript

I tried many things to pass data to my view, but i don't know what is wrong.
I tried with $scope and pass data with $state.go, but nothing happens.
.state('app.ler',
{
views: {
'menuContent': {
templateUrl: 'mensagens/mensagemRead.html',
controller: 'MensagensCtrl',
params: {'assunto': null}
}
},
url: '/ler'
})
$scope.read = function (id) {
MensagensService.ler(id).then(function (response) {
// $scope.mensagem_ler = response.data[0];
// alert(response.data[0].assunto);
$state.go('app.ler', {assunto:response.data[0].assunto});
console.log($stateParams);
});
};
<ion-view title="Mensagens2">
<ion-content class="has-header">
<div class="list">
<a class="item item-avatar" href="#">
<img src="venkman.jpg">
<h2>Gustavoaaa</h2>
<!--<p>{{mensagem_ler.assunto}}</p>-->
<p>{{assunto}}</p>
</a>
</div>
</ion-content>
</ion-view>

You can add the state parameter using a : in the url of your state.
.state('app.ler',
{
views: {
'menuContent': {
templateUrl: 'mensagens/mensagemRead.html',
controller: 'MensagensCtrl'
}
},
url: '/ler/:assunto'
});
This will make the property assunto available in $stateParams

params option of state is available in root level of state definition, you could not have them in leaf level of namedView.
.state('app.ler', {
views: {
'menuContent': {
templateUrl: 'mensagens/mensagemRead.html',
controller: 'MensagensCtrl',
}
},
url: '/ler/{assunto}', //here is parameter mentioned in URL
params: {
'assunto': null //parameter default value
}
})
You can get this values in $stateParams object inside your controller.

Try this in your state configurations
url: '/ler?assunto'
If you want to pass more parameters then just add them like this
url: '/ler?assunto&param2&param3....'
To use the state param in your view you can save it in a $scope variable in your controller and then use it.
For example: $scope.assunto = $stateParams.assunto;
<ion-view title="Mensagens2">
<ion-content class="has-header">
<div class="list">
<a class="item item-avatar" href="#">
<img src="venkman.jpg">
<h2>Gustavoaaa</h2>
<!--<p>{{mensagem_ler.assunto}}</p>-->
<p>{{assunto}}</p>
</a>
</div>
</ion-content>
</ion-view>

Related

AngularJS: Pass an object into a state using $state.go()

I'm trying to pass an object with $state.go() to another state , but the $stateParams is not getting populated .
I have tried everything I could find on web and stackoverflow , but none worked for me. thanks in advance for your help.
here is the code :
MyApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('productList', {
views:{
"main_view":{
templateUrl: 'pages/productList.html',
controller: 'productListController'
},
"second_view":{}
}
});
$stateProvider.state('productDetail', {
views:{
"main_view":{
templateUrl: 'pages/productDetail.html',
url:'/productDetail',
params:{
productObj: null
},
controller: 'productDetailController',
},
"second_view":{}
}
});
}
MyApp.controller('productListController',function($state,$scope,$http, $window){
$http
.get('api/item/index')
.then(function (response) {
$scope.items = response.data;
});
$scope.showProductDetails = function(argItem){
console.log(argItem); // will show the argItem object in logs
$state.go('productDetail',{productObj:argItem}); // here is the problem
}
});
MyApp.controller('productDetailController',function($stateParams,$state,$scope){
console.log($stateParams); //Empty
console.log($state.params) //Empty
});
<!-- using AngularJs v1.5.5 and ui-router v0.2.18 -->
<!-- this is pages/productList.html templateUrl page-->
<article ng-repeat="item in items">
<div class="thumbnail">
<a ng-click="showProductDetails(item)" class="btn btn-info">{{item.name}}</a>
</div>
</article>
the params : {} does not belong to view, but to state:
$stateProvider.state('productDetail', {
// this, state level, is a right place for params
params:{
productObj: null
},
views:{
"main_view":{
templateUrl: 'pages/productDetail.html',
url:'/productDetail',
// this is wrong place
// params:{
// productObj: null
// },
controller: 'productDetailController',
},
"second_view":{}
}
});

Nested Views with Dynamic Id's Angular & Rails

Hey I have Angular rendering a list of Quotes as resources. The Quotes are stored in a rails back end. I am at the point where I would like to use Angular to render the show.html for that specific quote resource.
I havent been able to get angular to resolve to the state.
I'm not sure if I understand how to pass id's into state.
I need help figuring out how to get angular to render the show.html in the ui-view labeled "fullquote" for the specific quote. Here is my code.
Quotes.html
<div class="quotes col-xs-10 col-md-8" ng-controller="QuotesCtrl" >
<div ng-repeat="quote in quotes">
<a ng-click="showQuote(quote);">
<span ng-if="quote.read == false"> *NEW*</span>
<span>Quote id: {{quote.id}}</span>
<span>Name: {{quote.name}}</span>
<span>Email: {{quote.email}}</span>
<span>City: {{quote.city}}</span>
<span>Region: {{quote.region}}</span>
<span>State: {{quote.state}}</span>
</a>
<div ng-show="quote.visible">
<a ui-sref="quotes/{{quote.id}}"> View </a>
<ui-view="fullquote"></ui-view="fullquote">
<a ng-click="quotes.splice($index, 1)"> Delete </a>
<div ng-if"">
<span> {{quote.question2 }}</span>
<span> {{quote.question3 }}</span>
<span> {{quote.question4 }}</span>
<span> {{quote.question5 }}</span>
<span> {{quote.question6 }}</span>
<span> {{quote.question7 }}</span>
<span> {{quote.question8 }}</span>
<span> {{quote.question9 }}</span>
<span> {{quote.question10 }}</span>
<span> {{quote.question11 }}</span>
<span> {{quote.question12 }}</span>
<span> {{quote.question13}}</span>
</div>
</div>
</div>
</div>
Quotes.js
app.factory('Quotes', ['$resource',function($resource){
return $resource('/quotes.json', {},{
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
}]);
app.factory('Quote', ['$resource', function($resource){
return $resource('/quotes/:id.json', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
});
}]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', { url: '', templateUrl: 'static_pages/home.html'})
.state('quotes', { url: '/quotes', abstract: false, views : { templateUrl: 'quotes.html', controller: 'QuotesCtrl'}})
.state('quotes/:id', { url: 'quotes/:id', view: { "fullquote": { templateUrl: 'show.html', controller: 'QuotesCtrl'}}})
.state('quotes/:id.pdf', { url: 'quotes/:id.pdf', controller: 'QuotesCtrl'})
.state('users', { url: '/users', templateUrl: 'users.html', controller: 'UsersCtrl'})
.state('/users/:id', { url: 'users_show.html', controller: "UsersCtrl" });
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("home");
})
$locationProvider.html5Mode({ enabled: true, requireBase: false });
});
app.controller("QuotesCtrl", ['$scope', '$state', '$http', 'Quotes', 'Quote', '$location', function($scope, $state, $http, Quotes, Quote, $location ) {
$scope.quotes = Quotes.query();
$scope.quote = Quote.query();
$scope.showQuote = function (quote) {
quote.visible = !quote.visible;
}
}]);
There are several things you should look into:
Your state naming is incorrect. I assume you are trying to use nested states.In this case you need to have quotes.detail or something of the kind. Also, in the state, you need to name your object views instead of view. Please, refer to UI.Router multiple views guide for more information.
.state('quotes.detail',
{ url: 'quotes/:id',
views: {
"fullquote": { templateUrl: 'show.html',
controller: 'QuoteCtrl'}
}
})
To pass a parameter to the state you need to change your link to this. If you'd like to know more about passing parameters to ui.router states - read the manual:
<a ui-sref="quotes.detail({{quote.id}})"> View </a>
If you want to have a separate view, you also need to have separate controller for it. I named it it QuoteController. You can get ht :id from the URL by injecting $stateParams in the controller. More info about getting parameters into the controllers - here:
//QuoteController
['$stateParams, Quote , function($stateParams, Quote) {
Quoute.get({id:$stateParams.id});
}]
I'm not sure this will completely solve your problem, but it will certainly bring you closer to solving it. I hope I was helpful!

State.go() shows the url in address page but doesn't refresh the html view

I have a problem when whorking on Ionic with angularJs, the problem is in routing system when I try to develop a login page .
In the controller part of code i'l trying to load a welcome page calle 'dash' with state.go(psc.dash)
here is my controller.js :
angular.module('starter.controllers', [])
.controller('LoginCtrl', function($location, $state) {
var user = this;
user.login = function() {
console.log("LOGIN user: " + user.email + " - PW: " + user.password);
setTimeout(function() {
state.go('psc.dash');
}, 20);
};
})
.controller('DashCtrl', function($scope, $location) {});
here is my App.js:
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('login', {
url: "/login",
views: {
'login': {
templateUrl: "templates/login.html",
controller: "LoginCtrl"
}
}
})
.state('psc', {
url: "/psc",
abstract: true,
templateUrl: "templates/psc.html"
})
.state('psc.dash', {
url: "/dash",
views: {
'psc-dash': {
templateUrl: "templates/dash.html",
controller: "DashCtrl"
}
}
})
;
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
and here is my login.html
<div class="list list col span_1_of_2 " ng-controller="LoginCtrl as loginCtrl">
<label class="item item-input">
<span class="input-label">E-mail</span>
<input type="text" ng-model="loginCtrl.email">
</label>
<label class="item item-input">
<span class="input-label">password</span>
<input type="password" ng-model="loginCtrl.password">
</label>
<div>
<div class="col span_2_of_3">forgot password ? </div>
<button class="button button-positive col span_1_of_3" ng-click="loginCtrl.login()">
connect
</button>
</div>
</div>
The problem is when I click on connect button the url '/psc/dash' appears in address bar but the login view stay displayed and the page is not reloaded with the new html view.
EDIT
This is wrong. There is a discrepancy in the ui-router documentation: states that inherit from an abstract state are prefixed with their parents URL.
The reason is that although your 'psc.dash' nested state is defined as a child of the 'psc' state, the URL you have assigned to it is not automatically prefixed with its parent's URL.
You want to change the 'psc.dash' state definition to this:
.state('psc.dash', {
url: "/psc/dash",
views: {
'psc-dash': {
templateUrl: "templates/dash.html",
controller: "DashCtrl"
}
}
})
Take a look at the ui-router documentation for why this is:
What Do Child States Inherit From Parent States?
Child states DO inherit the following from parent states:
Resolved dependencies via resolve Custom data properties
Custom data properties
Nothing else is inherited (no controllers, templates, url, etc).
The service is $state so the code should be:
$state.go('psc.dash');
You can get rid of the controller definition in your HTML:
<div class="list list col span_1_of_2" ng-controller="LoginCtrl as loginCtrl">
</div>
use this instead:
<div class="list list col span_1_of_2">
</div>
and change the state this way:
.state('login', {
url: "/login",
views: {
'login': {
templateUrl: "templates/login.html",
controller: "LoginCtrl as loginCtrl"
}
}
})
You don't need to define the controller twice.
Your login.html template does not use <ion-view>. It would be interesting to see a plunker of your project.
Another things I am not sure about is the state definition. If the view login is not wrapped in another container you should write it like this:
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
controller: "LoginCtrl as loginCtrl"
})
SOLUTION:
my psc route should be named 'login' to be identified
.state('psc', {
url: "/psc",
views: {
'login': {
abstract: true,
templateUrl: "templates/psc.html"
}
}
})

Controller being called twice in Ionic (AngularJS)

In my angular project the user accepts a EULA then get automatically redirected to their dashboard, however, on this redirect the DashboardController seems to be being called twice, the DashboardController is being called on the route itself, I have checked to see if I have accidently called it again in the template but I havn't. Below is my route & controller. It doesn't appear to matter if I access the URL directly or via the redirect on the EULA controller, I get the same result.
The routes
.config(function($httpProvider, $stateProvider, $urlRouterProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login', {
url: '/',
templateUrl: 'templates/login.html',
data: {
requireLogin: false
}
})
.state('eula', {
url: '/eula',
templateUrl: 'templates/eula.html',
data: {
requireLogin: true
}
})
.state('dashboard', {
url: '/groups',
templateUrl: 'templates/dashboard.html',
data: {
requireLogin: true
}
})
});
The controller:
App.controller('DashboardController', ['$scope', 'RequestService', '$state', '$rootScope', function($scope, RequestService, $state, $rootScope){
alert('test');
}]);
Any ideas?
ADDED MY HTML AS PER COMMENTS
index.html
<body ng-app="App">
<ion-nav-bar class="bar-positive nav-title-slide-ios7" align-title="center">
<ion-nav-back-button class="button-icon ion-arrow-left-c"></ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view class="slide-left-right"></ion-nav-view>
<ui-view></ui-view>
</body>
dashboard.html
<div class="groups" ng-controller="DashboardController">
<ion-view title="App">
<ion-nav-buttons side="right">
<a ui-sref="groupcreate"><span class="icon ion-ios-plus-outline"></span></a>
</ion-nav-buttons>
<ion-content class="padding">
<div class="row">
<div class="col-50" ng-repeat="group in groups">
{{ group }} 1
</div>
</div>
</ion-content>
</ion-view>
</div>
If you are using ui-router you don't have to use ng-controller. You have used it in your dashboard.html, another is generated by ui-router - that's why it is hit twice.
Ok so after a long time debugging and check stuff out, I found out that it was an issue relating to the Nav Bar in ionic, essentially, I was calling <ui-view></ui-view> & <ion-nav-view></ion-nav-view> on the same page, so basically doubling up on my views which in turn was calling the controller twice.
I know this has been answered already as well, but I wanted to add my fix for the exact same problem.
My controllers were also being called twice, but in my case I had to comment out the ng-controller settings in various files:
My config function in the main app.js
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('splash', {
url: "/",
templateUrl: "app/splash/splash.html"
// controller: 'SplashCtrl'
})
Since I was already calling it in the markup:
<ion-view view-title="TickerTags" ng-controller="SplashCtrl as splash">
<ion-content class="splash">
The controller key inside of my Directives
angular
.module('tagsPanelDirective', [])
.controller('TagsPanelCtrl', TagsPanelCtrl)
.directive('tagsPanel', tagsPanel);
function tagsPanel() {
var directive = {
templateUrl: "app/tags/tagsPanel.html",
restrict: "E",
replace: true,
bindToController: true,
// controller: 'TagsPanelCtrl as tagsPanel',
link: link,
scope: false
};
return directive;
function link(scope, element, attrs) {}
}
Again since I was already calling it from within the template markup:
<section class="tags-panel" ng-controller="TagsPanelCtrl as tagsPanel">

Angular.js $scope and controller again

I know there are many questions regarding the angular $scope by after a couple of hours I still can't figure out what is wrong. I'm using Angular.js with Ionic but the problem should be angular related.
In my App I need a "add to wishlist" function. In the productDetail view when someone tapps "add to wishlist" I add this product with a service and webSQL to the database. Now when the user goes to the wishlist view I get all saves products but the view doesn't update.
I have a file menu.html with an Ionic side-menu:
<ion-side-menu side="left" expose-aside-when="large" width="72">
<ion-content>
<ion-list ng-controller="LeftMenuCtrl">
<ion-item nav-clear menu-close ng-href="#/app/wish" ng-click="updateWishList()" ng-class="{'current': isActive('/app/wish')}">
<span class="icon icon-menu-wish"></span>
</ion-item>
</ion-list>
</ion-content>
</ion-side-menu>
The "LeftMenuCtrl" handels the hover for the active menu item.
In my WishListView I would like to show the current added products:
File wishList.html
<ion-view hide-nav-bar="true" view-title="WISHLIST" ng-controller="WishlistCtrl">
<div class="bar bar-header bar-stable">
<div class="header-wrapper">
<!--heading-->
<div class="dash-slider-wrapper"" >
<div class="header-text-main">WHISH</div> <div class="header-text-sub">LIST</div>
</div>
</div>
</div>
<ion-content class="has-header">
<ion-item class="product-card" ng-repeat="product in products">
<div class="card">
EAN: {{product.ean}}
</div>
</ion-item>
</ion-content>
</ion-view>
And the controller:
app.controller("WishlistCtrl", function($scope, $state, productService) {
//gets called when the controller is loaded
productService.getWishlistProducts().then(function (products) {
$scope.products = products;
});
//gets called when the user clicks on the navi but does not
//update the $scope (or it updates the wrong $scope)
$scope.updateWishList = function () {
productService.getWishlistProducts().then(function (products) {
$scope.products = products;
});
};
})
Can anyone tell me whats wrong here please?
Edit:
This is the state for the menu link:
.state('app.wish', {
url: "/wish",
views: {
'menuContent': {
templateUrl: "templates/wish.html"
}
}
})
Edit2:
When I refresh the page, I see all added products. But not immediately. It's like the
$scope.updateWishList = function () ...
creates another $scope...
Edit3:
app.controller('ProductDetailCtrl', function($stateParams ,$state, $scope, productService, $ionicHistory, $ionicPopup) {
$scope.addToWishlist = function(ean) {
productService.addProductToWishlist(ean).then(function(response) {
if(response == "OK") {
var alertPopup = $ionicPopup.alert({
title: 'product added to wishlist',
template: 'You can go to your wishlist to see all your marked products'
});
}
});
};
})
Edit4:
I added a Plunker here: http://plnkr.co/edit/0woPfN
It´s not working but you can see the code there (I deleted unnecessary stuff)
Your problem is that you have 2 declaration of the WishlistCtrl.
Once in the app.js:
.state('app.wish', {
url: "/wish",
views: {
'menuContent': {
templateUrl: "wish.html",
controller: 'WishlistCtrl' //here is the first declaration
}
}
})
Second in the HTML:
<ion-view hide-nav-bar="true" view-title="WISHLIST" ng-controller="WishlistCtrl">
Remove either one and you'll be fine.
Finally, I got it working.
First in the StateProvicer I added a resolve method:
.state('app.wish', {
url: "/wish",
views: {
'menuContent': {
templateUrl: "templates/wish.html",
controller: 'WishlistCtrl',
resolve: {
products: function(productService) {
return productService.getWishlistProducts()
}
}
}
}
})
And to update the model when a new product gets added to the wishlist:
.controller("WishlistCtrl", function($scope, $state, productService, products) {
//set wishlist products on controller load
$scope.products = products;
//updated wishlist when a new product gets added
$rootScope.$on('updatedWishList', function() {
console.log('List has been updated. ');
productService.getWishlistProducts().then(function (products) {
$scope.products = products;
});
});
})
Easy... when you know how :D

Categories