I'm trying to create To Do List app with ui-router. I can create task, delete but i cannot edit my task because of this problem. Can anyone help me?
Transition Rejection($id: 2 type: 6, message: The transition errored, detail: Error: Transition Rejection($id: 1 type: 4, message: This transition is invalid, detail: The following parameter values are not valid for state 'second': [todoText:undefined]))
var app = angular.module('app', [
'ui.router',
'todoApp.services',
'todoApp.controllers'
]);
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('first', {
url: '/new',
templateUrl: 'detail.html',
controller: 'CreateCtrl'
})
.state('second', {
url: '/edit/:todoText',
controller: 'EditCtrl',
templateUrl: 'detail.html'
})
.state('third', {
url: '/',
controller: 'ListCtrl',
templateUrl: 'list.html'
})
.state('root', {
controller: 'ListCtrl',
templateUrl: 'list.html'
})
}]);
app.controller('EditCtrl', function ($scope, $location, $stateParams, Todos) {
$scope.todos = Todos;
var result = $scope.todos.filter(function (obj) {
return obj.text == $stateParams.todoText;
}); console.log(result);
$scope.todoText = result[0].text;
$scope.todoDetails = result[0].details;
$scope.todoDate = result[0].date;
console.log(result);
$scope.save = function () {
var text = $scope.todoText;
var details = $scope.todoDetails;
var done = $scope.todoDone;
var date = $scope.todoDate;
alert(text);
angular.forEach($scope.todos, function (todo) {
if (todo.text == text) {
todo.text = text;
todo.details = details;
todo.date = date;
}
});
$location.path('/');
};
});
app.factory('Todos', function () {
var items = [
]
return items;
});
<!-- html button -->
<button class="btn btn-light">
<a ui-sref='second()'>
<i class="fas fa-edit"></i>Edit</i>
</a>
</button>
You have a state second that expects a parameter todoText:
.state('second', {
url: '/edit/:todoText',
controller: 'EditCtrl',
templateUrl: 'detail.html'
})
The problem is that when you call that state you don't pass any parameter:
<a ui-sref='second()'>
Here you need to add the todoText parameter like this:
<a ui-sref='second({todoText: todo.text})'>
#Bill P helped. Thank you.
<a ui-sref='second({todoText: todo.text})'>
Related
I am creating webpage with webpack and Ive got strange error.
Data must be a valid JSON object. Received: ".... Undefined
index: id
So, I checked my objects which i sending. Then, when my service to get ID returns something like this in console log:
ƒ (){
return id;
}
So, I know that I've to run function first, then html template. Where I can get the error if we are talking about webpack?
It's my app.js, where I configure service and templates with controllers:
const css = require('./src/style/app.scss');
var angular = require('angular');
var ngRoute = require('angular-route');
var ngModule = angular.module('app', ['ngRoute']);
require('./src/js/contact')(ngModule);
require('./src/js/adminNetworks')(ngModule);
require('./src/js/automatic')(ngModule);
require('./src/js/login')(ngModule);
require('./src/js/program')(ngModule);
require('./src/js/register')(ngModule);
require('./src/js/main')(ngModule);
ngModule.service('user', function(){
var username;
var loggedin = false;
var id;
this.getName = function(){
return username;
};
this.setID = function(userID){
id = userID;
};
this.getID = function(){
return id;
};
this.isUserLoggedIn = function(){
if(!!localStorage.getItem('login')){
loggedin = true;
var data = JSON.parse(localStorage.getItem('login'));
username = data.username;
id = data.id;
}
return loggedin;
};
this.saveData = function(data){
username = data.user;
id = data.id;
loggedin = true;
localStorage.setItem('login', JSON.stringify({
username: username,
id: id
}));
};
this.clearData = function(){
localStorage.removeItem('login');
username="";
id="";
loggedin = false;
}
})
ngModule.controller('IndexController', ['$scope', 'user', function ($scope, user) {
$scope.aa = function(){
console.log(user.get);
}
}])
ngModule.config(function($routeProvider, $locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.when('/program', {
templateUrl: 'program.html',
controller: 'ProgramCtrl',
resolve: {
check: function($location, user){
if(!user.isUserLoggedIn()){
$location.path('/');
alert('Musisz być zalogowany')
}
}
}
})
.when('/administration', {
templateUrl: 'adminNetworks.html',
controller: 'NetworkCtrl'
})
.when('/automatic', {
templateUrl: 'automatic.html',
controller: 'AutomaticCtrl'
})
.when('/contact', {
templateUrl: 'contact.html',
controller: 'ContactCtrl'
})
.when('/registry', {
templateUrl: 'register.html',
controller: 'RegisterCtrl'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginCtrl'
})
.when('/logout', {
resolve: {
deadResolve: function($location, user){
user.clearData();
$location.path('/');
}
}
})
.otherwise({
redirectTo: "/"
});
});
Firstly, I thought, that it's because of load chunks like this:
plugins: [
new HtmlWebpackPlugin({
title: 'Główna',
hash: true,
allChunks: true,
template: './src/html/index.html'
}),
new HtmlWebpackPlugin({
title: 'Main',
hash: true,
chunks: ['main'],
filename: 'main.html',
template: './src/html/main.html'
}),
but when I removed chunks section, it's still the same.
Please at least for any ideas.
#Edit - my new pass sender:
module.exports = function(ngModule) {
ngModule.controller('MainCtrl', ['$scope', '$http','user', function ($scope, $http, user) {
$scope.user = user.getName();
console.log("LOCAL STORAGE");
console.log(localStorage);
$scope.newPass = function(){
debugger;
var password = $scope.newpassword;
$http({
url: 'http://localhost/webpack/updatePass.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'newPass='+password+'&id='+user.getID()
}).then(function(response){
if(response.data.status =='done') {
alert('Changed');
}else {
alert('error');
}
})
}
}])
}
https://plnkr.co/edit/PWuKuVw9Dn9UJy6l8hZv?p=preview
I have 3 modules, routerApp, tickers and tags. Basically trying to rebuild my app out of smaller mini-apps.
The routerApp template contains the 2 directives for the other modules.
Expected
When you login, then click on the Count button in the tickers.component, I want to send the counter var into the tags.component $scope via $state.go.
Result
Nothing happens. No $state/variable update in the tags.component
Plnkr app.js code:
// TICKERS app module
var tickers = angular.module('tickers', ['ui.router'])
tickers.config(function($stateProvider) {
const tickers = {
name: 'tickers',
url: '/tickers',
parent: 'dashboard',
templateUrl: 'tickers-list.html',
bindToController: true,
controllerAs: 'tik',
controller: function() {
}
}
$stateProvider
.state(tickers);
})
tickers.component('tickersModule', {
templateUrl: 'tickers-list.html',
controller: function($scope, $state) {
console.log('Tickers init')
$scope.counter = 0;
$scope.increase = function() {
$scope.counter++;
console.log('increase', $scope.counter)
$state.go('dashboard.tags', { counter: $scope.counter });
}
}
})
// TAGS app module
var tags = angular.module('tags', ['ui.router'])
tags.config(function($stateProvider) {
const tags = {
name: 'tags',
url: '/tags?counter',
parent: 'dashboard',
params: {
counter: 0
},
templateUrl: 'tags-list.html',
bindToController: true,
controllerAs: 'tags',
controller: function($state) {
}
}
$stateProvider
.state(tags);
})
tags.component('tagsModule', {
templateUrl: 'tags-list.html',
controller: function($scope, $state) {
// Expecting this to update:
console.log('Tags init', $state)
$scope.counter = $state.params.counter;
}
})
// MAIN ROUTERAPP module
var routerApp = angular.module('routerApp', ['ui.router', 'tickers', 'tags']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
const login = {
name: 'login',
url: '/login',
templateUrl: 'login.html',
bindToController: true,
controllerAs: 'l',
controller: function($state) {
this.login = function() {
$state.go('dashboard', {})
}
}
}
const dashboard = {
name: 'dashboard',
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: function() {
}
}
$stateProvider
.state(login)
.state(dashboard);
})
dashboard.html
<div class="jumbotron text-center">
<h1>The Dashboard</h1>
</div>
<div class="row">
<tickers-module></tickers-module>
<tags-module></tags-module>
</div>
The function in the tickers component that is trying to update the $state of the tags component:
$scope.increase = function() {
$scope.counter++;
console.log('increase', $scope.counter)
$state.go('dashboard.tags', { counter: $scope.counter });
}
Also tried: $state.go('tags', { counter: $scope.counter });
Finally the tags.component.
Note that here I'm not seeing the $scope.counter update nor the controller for the component getting refreshed due to a state change.
tags.component('tagsModule', {
templateUrl: 'tags-list.html',
controller: function($scope, $state) {
console.log('Tags init', $state)
$scope.counter = $state.params.counter;
}
})
Is the way I am architecting this going to work? What am I missing?
Update: Added some $rootScope events to watch for $state changes, hope this helps:
This is after clicking the login button and going from the login state to the dashboard state, but still nothing for clicking on the Count button.
So, it looks like you're properly passing the parameters in your $state.go call.
I think the issue here is that you're not properly handling the state parameters you're passing from the tickers component to the tags component.
Try injecting $stateParams into your tags component and pull the parameters off that object, for example (in your tags controller):
$scope.counter = $stateParams.counter;
Figured it out!
https://plnkr.co/edit/CvJLXKYh8Yf5npNa2mUh?p=preview
My problem was that in the $state object tags, I was using the same template as the tags.component.
Instead I needed to change it to something like <p>{{ counter }}</p>
var tags = angular.module('tags', ['ui.router'])
tags.config(function($stateProvider) {
const tags = {
name: 'tags',
url: '/tags',
parent: 'dashboard',
params: {
counter: 0
},
template: '<p>{{ counter }}</p>',
bindToController: true,
controller: function($scope, $state) {
console.log('tags state object', $state)
$scope.counter = $state.params.counter;
}
}
$stateProvider
.state(tags);
})
tags.component('tagsModule', {
templateUrl: 'tags-module-template.html',
controller: function($scope, $state) {
}
})
Then in my tags-module.template.html I needed to add a <div ui-view></div>
<div class="jumbotron text-center">
<h2>Tags list</h2>
<div ui-view></div> // <- here and this is where the $state object updates
{{ counter }}
</div>
https://codepen.io/anon/pen/VaBOwv
.controller('CheckinCtrl', function($scope) {
$scope.$root.showRight = true;
})
.controller('AttendeesCtrl', function($scope) {
$scope.$root.showRight = false;
alert($scope.$root.showRight)
});
I use ng-show to show hide the right button on menu. But when I try it vice-versa I found that the value of the scope isn't updating due to cache. I dislike to use cache:false in the state because it's such a bad experience for the user. But how to solve this issue?
http://ionicframework.com/docs/api/directive/ionView/
On entering a new view, $ionicView.enter will be broadcast to $scope, that's the place to put your code, if you want your code to be executed every time user enters the view.
Change your code to
angular.module('ionicApp', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('eventmenu', {
url: "/event",
abstract: true,
templateUrl: "templates/event-menu.html"
})
.state('eventmenu.home', {
url: "/home",
views: {
'menuContent' :{
templateUrl: "templates/home.html"
}
}
})
.state('eventmenu.checkin', {
url: "/check-in",
views: {
'menuContent' :{
templateUrl: "templates/check-in.html",
controller: "CheckinCtrl"
}
}
})
.state('eventmenu.attendees', {
url: "/attendees",
views: {
'menuContent' :{
templateUrl: "templates/attendees.html",
controller: "AttendeesCtrl"
}
}
})
$urlRouterProvider.otherwise("/event/home");
})
.controller('MainCtrl', function($scope, $ionicSideMenuDelegate) {
$scope.$root.showRight = true;
$scope.toggleLeft = function() {
$ionicSideMenuDelegate.toggleLeft();
};
})
.controller('CheckinCtrl', function($scope) {
$scope.$on("$ionicView.enter",function(){
$scope.$root.showRight = true;
});
})
.controller('AttendeesCtrl', function($scope) {
$scope.$on("$ionicView.enter",function(){
$scope.$root.showRight = false;
});
// alert($scope.$root.showRight)
});
And it should work
I'm running out of idea right now. Everything seems fine, but when Im trying to inherit master data into the details view nothing really shows when I consoled except for the id.
Console Output : Object {id: "78"}
Here's my code :
Config
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "templates/home.html",
controller: 'PostHomeCtrl'
}
}})
.state('app.posthome', {
url: "/home/:id",
views: {
'menuContent': {
templateUrl: 'templates/post.html',
controller: 'PostDetailCtrl'
}
}})
Factory
.factory('Posts', function($http){
var blogs = []; //Private Variable
return {
GetBlog: function(){
return $http.get('path/to/resources').then(function(response){
blogs = response;
return response;
});
},
GetPost: function(postId){
for(i=0;i<blogs.length;i++){
if(blogs[i].id == postId){
return blogs[i];
}
}
return null;
}
}})
Controller
.controller('PostHomeCtrl', function(Posts, $scope){
Posts.GetBlog().then(function(blogs){
$scope.blogs = blogs.data;
console.log(blogs.data);
});
})
.controller('PostDetailCtrl', function(Posts, $stateParams, $scope){
var postId = $stateParams;
$scope.blog = Posts.GetPost(postId);
console.log(postId);
});
nvm just figured it out, turns out my I forgot to add .data at my blog = response . So it becomes blog=response.data instead of blog=response. Thanks
I am trying to create a "Todo App" with angularjs ui-router. It has 2 columns:
Column 1: list of Todos
Column 2: Todo details or Todo edit form
In the Edit and Create controller after saving the Todo I would like to reload the list to show the appropriate changes. The problem: after calling $state.go('^') when the Todo is created or updated, the URL in the browser changes back to /api/todo, but the ListCtrl is not executed, i.e. $scope.search is not called, hence the Todo list (with the changed items) is not retrieved, nor are the details of the first Todo displayed in Column 2 (instead, it goes blank).
I have even tried $state.go('^', $stateParams, { reload: true, inherit: false, notify: false });, no luck.
How can I do a state transition so the controller eventually gets executed?
Source:
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos) {
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos.concat(data);
$state.go('todo.details', { id: $scope.todos[0].Id });
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
$state.go('^', $stateParams, { reload: true, inherit: false, notify: false });
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
$state.go('^');
});
};
};
I would give an example (a draft) of HOW TO nest edit into detail. Well, firstly let's amend the templates.
The Detail template, contains full definition of the detail. Plus it now contains the attribute ui-view="editView". This will assure, that the edit, will "replace" the detail from the visibility perspective - while the edit scope will inherit all the detail settings. That's the power of ui-router
<section ui-view="editView">
<!-- ... here the full description of the detail ... -->
</section>
So, secondly let's move the edit state, into the detail
// keep detail definition as it is
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
// brand new definition of the Edit
.state('todo.details.edit', { // i.e.: url for detail like /todo/details/1/edit
url: '/edit',
views: {
'editView': { // inject into the parent/detail view
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
Having this adjusted state and template mapping, we do have a lot. Now we can profit from the ui-router in a full power.
We'll define some methods on a DetailCtrl (remember, to be available on the inherit Edit state)
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.id = $stateParams.id // keep it here
// model will keep the item (todos) and a copy for rollback
$scope.model = {
todos : {},
original : {},
}
// declare the Load() method
$scope.load = function() {
Todos
.get({ id: $stateParams.id })
.then(function(response){
// item loaded, and its backup copy created
$scope.model.todos = response.data;
$scope.model.original = angular.copy($scope.model.todos);
});
};
// also explicitly load, but just once,
// not auto-triggered when returning back from Edit-child
$scope.load()
};
OK, it should be clear now, that we do have a model with the item model.todos and its backup model.original.
The Edit controller could have two actions: Save() and Cancel()
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
// ATTENTION, no declaration of these,
// we inherited them from parent view !
//$scope.id .. // we DO have them
//$scope.model ...
// the save, then force reload, and return to detail
$scope.save = function () {
Todos
.update({ id: id })
.then(function(response){
// Success
$scope.load();
$state.go('^');
},
function(reason){
// Error
// TODO
});
};
// a nice and quick how to rollback
$scope.cancel = function () {
$scope.model.todos = Angular.copy($scope.model.original);
$state.go('^');
};
};
That should give some idea, how to navigate between parent/child states and forcing reload.
NOTE in fact, instead of Angular.copy() I am using lo-dash _.cloneDeep() but both should work
Huge thanks for Radim Köhler for pointing out that $scope is inherited. With 2 small changes I managed to solve this. See below code, I commented where I added the extra lines. Now it works like a charm.
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos) {
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos(data); // No concat, just overwrite
if (0 < $scope.todos.length) { // Added this as well to avoid overindexing if no Todo is present
$state.go('todo.details', { id: $scope.todos[0].Id });
}
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
$scope.search(); // Added this line
//$state.go('^'); // As $scope.search() changes the state, this is not even needed.
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
$scope.search(); // Added this line
//$state.go('^'); // As $scope.search() changes the state, this is not even needed.
});
};
};
I might have faced a similar problem the approach i took was to use $location.path(data.path).search(data.search); to redirect the page then in the controller I caught the $locationChangeSuccess event. I other words I use the $location.path(...).search(...) as apposed to $state.go(...) then caught the $locationChangeSuccess event which will be fired when the location changes occurs before the route is matched and the controller invoked.
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos, todo.details) {
/*here is where i would make the change*/
$scope.$on('$locationChangeSuccess', function () {
$scope.search();
$route.reload();
});
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos.concat(data);
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos, $location) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
//here is where I would make a change
$location.path('todo.details').search($stateParams);
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos, $location) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
//here is where I would make a change
$location.path('todo.details');
});
};
};
the $locationChangeSuccess event occurs before the route is matched and the controller invoked