AngularFire - Error: Could not resolve '#/tabpost' from state 'tabdash' [duplicate] - javascript

This question already has answers here:
AngularFire - How to define item ID for child template with ng-repeat?
(2 answers)
Closed 7 years ago.
Maybe my issue seems easy to resolve, but I've this problem since a lot of hours : When I'm in my dashboard, all data of my Firebase database are visible (With Ng-repeat).
But I can't found a solution for choose one specific item and see his details in another page.
I've test this method above and I've this error "Error: Could not resolve '#/tabpost' from state 'tabdash".
This is the HTML (This is an example) :
<div ng-repeat="post in posts">
<div class="card" ui-sref="#/post/{id}">
<h1>{{post.title}}</h1>
<p>{{post.content}}</p>
</div>
</div>
In App JS :
.state('tabpost', {
url: 'tabpost/id',
templateUrl: 'templates/tab-post.html',
controller: 'PostCtrl'
})
In Service JS (in Post Factory) :
myApp.factory("Post", ["$firebaseArray", "$firebaseObject", function($firebaseArray, $firebaseObject) {
var postRef = new Firebase('https://myApp.firebaseio.com/Posts/');
var userRef = new Firebase('https://myApp.firebaseio.com/Users/');
var posts = $firebaseArray(postRef);
var Post = {
all: posts,
get: function (postKey){
var postId = $firebaseObject(postRef);
return $firebaseObject(eventRef.child('Posts').child(postId).child(userid));
}
,
add: function (post){
var postId = $firebaseArray(postRef, userRef);
event.userid = userRef.getAuth();
return postId.$add(post);
}
}
return Post;
}]);
My PostCtrl :
myApp.controller('PostCtrl', ['$ionicFrostedDelegate', '$ionicScrollDelegate','$state','$scope', 'Post', 'Auth', '$firebaseObject', '$firebaseArray', '$routeParams', function($ionicFrostedDelegate, $ionicScrollDelegate, $state,$scope, Post, Auth, $firebaseObject, $firebaseArray, $routeParams) {
var PostRef = new Firebase("https://myApp.firebaseio.com/Posts");
var id = $routeParams.id; //get the id from url, $routeParams is injected in controller
$state.go('tabpost', {
id: $scope.id
});
$scope.posts = Post.get(id); //call get() method of Post with the id retrieved
$scope.post = {'title': '', 'content': ''};
$scope.auth = Auth;
PS : It took 3 days and night to try a bunch of tutorials mostly obsolete , and I am sure that the solution can not be that simple.
I already posted three similar issues yesterday and later but each of the proposed solutions have not worked . I would be immensely grateful to the person who would help me out of this impasse .
I still have a little trouble with jsFiddle promised I would learn to use it once I would have solved this problem.
Thank you for giving me time

You need to prefix your variable names with a colon in your state's URL. Your ui-router state should be
.state('tabpost', {
url: 'tabpost/:id',
templateUrl: 'templates/tab-post.html',
controller: 'PostCtrl'
});
and you should link to it like
<div class="card" ui-sref="tabpost/{id}">

Related

Is there any Better way for Routing the page

I am new to Angular js. I have created simple login page. My code is working perfectly. But I want it to route the page , when I login. I went through some of the blog , but I din't got the better approach.
I have created a plunker. Please check it out here.
https://plnkr.co/edit/9O5dHYZMKAqF07y7moVT
Formerly known as Angular then as Angular 1.x is now called AngularJS.
Notice it's one word :)
In order to change a route inside a controller.
( I assume this is what you mean by question since I see some playing with the login information.)
You can use $location.
$location.path(path-to-where-you-wanna-go);
You also need to tell injector to use $location, so your complete controller would look like:
app.controller('credientials', function($scope, $location, authentication) {
$scope.name = 'World';
$scope.cred = 'admin/123';
$scope.templates =
[
{ url: 'login.html' },
{ url: 'practice.html'}
];
$scope.template = $scope.templates[0];
$scope.loginform = function (username, password) {
if ( $scope.username === 'admin' && $scope.password === '123') {
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.user = username;
$scope.info = authentication.isAuthenticated;
$location.path( "/practice" );
} else {
$scope.error = "Invalid username and password";
}
};
});
Assuming you wanna go to /practice route. Note, that you do lack the template and controllers for outer routes. Without it, it won't work.

Angular JS UI-Routing with stateparams not working after refresh

Using angular-ui-router with angular for routing in MEAN application
angular: 1.6.2,
angular-ui-router: 0.4.2
Having following state:
.state('myposts', {
url: '/your-posts',
controller:'PostListController',
templateUrl:'post-list.template.html'
})
.state('postdetail', {
url: '/post/:postId',
controller:'PostDetailController',
templateUrl:'postdetail.template.html',
resolve:{
postdetail: ['Post', '$stateParams', function (Post, $stateParams) {
var url = '/api/posts/edit/' + $stateParams.postId;
return Post.get(url);
}]
}
})
In post-list.template.html listed all posts in table and there is an link to edit particular post by using the following
<a ui-sref="postdetail({ postId: post._id })" class="btn btn-default">
It makes an transition from myposts to postdetail with postId parameter.
Actual URL http://localhost:8886/#/post/58d5167bf05b904a52158f58
Here postId is 58d5167bf05b904a52158f58
Resolve post with postId = 58d5167bf05b904a52158f58 in resolve property of ui-router and inject in PostDetailController controller
function PostDetailController($scope, $state, $stateParams, postdetail, Post){
$scope.post = postdetail;
....
}
It works normally first time, but not working when i refresh the page having url
http://localhost:8886/#/post/58d5167bf05b904a52158f58
Using express server ^4.13.4,
Anyone having solution of above problems, why it is happening
Thanks

AngularFire - How to define item ID for child template with ng-repeat?

Maybe my issue seems easy to resolve, but I've this problem since a lot of hours : When I'm in my dashboard, all data of my Firebase database are visible (With Ng-repeat).
But I can't found a solution for choose one specific item and see his details in another page.
I've test this method in HTML (This is an example) :
<div ng-repeat="post in posts">
<div class="card" ng-href="#/post/">">
<h1>{{post.title}}</h1>
<p>{{post.content}}</p>
</div>
</div>
In App JS :
.state('tabpost', {
url: 'tabpost/id',
templateUrl: 'templates/tab-post.html',
controller: 'PostCtrl'
})
In Service JS (in Post Factory) :
myApp.factory("Post", ["$firebaseArray", "$firebaseObject", function($firebaseArray, $firebaseObject) {
var postRef = new Firebase('https://myApp.firebaseio.com/Posts/');
var userRef = new Firebase('https://myApp.firebaseio.com/Users/');
var posts = $firebaseArray(postRef);
var Post = {
all: posts,
get: function (postKey){
var postId = $firebaseObject(postRef);
return $firebaseObject(eventRef.child('Posts').child(postId).child(userid));
}
,
add: function (post){
var postId = $firebaseArray(postRef, userRef);
event.userid = userRef.getAuth();
return postId.$add(post);
}
}
return Post;
}]);
My PostCtrl :
myApp.controller('PostCtrl', ['$ionicFrostedDelegate', '$ionicScrollDelegate','$state','$scope', 'Post', 'Auth', '$firebaseObject', '$firebaseArray', function($ionicFrostedDelegate, $ionicScrollDelegate, $state,$scope, Post, Auth, $firebaseObject, $firebaseArray) {
var PostRef = new Firebase("https://myApp.firebaseio.com/Posts");
$scope.posts = Post.all;
$scope.post = {'title': '', 'content': ''};
$scope.auth = Auth;
PS : It took 16 hours to try a bunch of tutorials mostly obsolete , and I am sure that the solution can not be that simple.
I already posted two similar issues yesterday and this morning but each of the proposed solutions have not worked . I would be immensely grateful to the person who would help me out of this impasse .
I still have a little trouble with jsFiddle promised I would learn to use it once I would have solved this problem.
Thank you for giving me time
Can you please try the following set of codes, I've explained the changes in comments in Controller and added :id in App JS
In App JS :
.state('tabpost', {
url: 'tabpost/:id',
templateUrl: 'templates/tab-post.html',
controller: 'PostCtrl'
})
PostCtrl :
myApp.controller('PostCtrl', ['$ionicFrostedDelegate', '$ionicScrollDelegate','$state','$scope', 'Post', 'Auth', '$firebaseObject', '$firebaseArray', '$routeParams', function($ionicFrostedDelegate, $ionicScrollDelegate, $state,$scope, Post, Auth, $firebaseObject, $firebaseArray, $routeParams) {
var PostRef = new Firebase("https://myApp.firebaseio.com/Posts");
var id = $routeParams.id; //get the id from url, $routeParams is injected in controller
$scope.posts = Post.get(id); //call get() method of Post with the id retrieved
$scope.post = {'title': '', 'content': ''};
$scope.auth = Auth;
you can use route provider to do that. I used that for my application and it works great.
myApp.config( ['$routeProvider', function($routeProvider){
$routeProvider.
when('tabpost', {
templateUrl: 'tabpost/id',
controller: 'PostCtrl'
});
}]);

angular promise - on submit gets "Error: args is null $parseFunctionCall"

I am currently following this tuto on MEAN.js : https://thinkster.io/mean-stack-tutorial/ .
I am stuck into the end of "Wiring Everything Up", I am completlty new to angular so I am not pretending I understood everything I did. Here is the situation :
We are using the plugin ui-router.
First here is the html template :
<form name="addComment" ng-submit="addComment.$valid && addComment()"novalidate>
<div class="form-group">
<input class="form-control" type="text" placeholder="Comment" ng-model="body" required/>
</div>
<button type="submit" class="btn btn-primary">Comment</button>
</form>
The error "Error: args is null $parseFunctionCall" occurs only when I submit the form
Then, here is the configuration step for this page :
app.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('posts', {
url : '/posts/{id}',
templateUrl: '/posts.html',
controller : 'PostsCtrl',
resolve : {
post: ['$stateParams', 'posts', function ($stateParams, posts) {
return posts.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
There, is the controller :
app.controller('PostsCtrl', ['$scope', 'posts', 'post',
function ($scope, posts, post) {
$scope.post = post;
$scope.addComment = function () {
posts.addComment(post._id, {
body : $scope.body,
author: 'user'
}).success(function (comment) {
$scope.post.comments.push(comment);
});
$scope.body = '';
};
$scope.incrementUpVote = function (comment) {
posts.upvoteComment(post, comment);
};
}]);
And Finally, the factory where the posts are retrieved from a remote webservice
app.factory('posts', ['$http', function ($http) {
var o = {
posts: []
};
o.get = function (id) {
return $http.get('/posts/' + id).then(function (res) {
return res.data;
});
};
o.addComment = function (id, comment) {
return $http.post('/posts/' + id + '/comments', comment);
};
return o;
}]);
I've only given the parts that I think are relevant.
I suspect that the problem is comming from the promise and the scope which have been unlinked. I searched about promises but I think that ui-router is doing it differently.
I tried some $watch in the controller but without succeding.
Has anyone some idea about that ? Thank you in advance
The form name addComment (used for addComment.$valid) and the function addComment added to the scope are clashing with each other, rename one or the other.
See the Angular docs for the form directive:
If the name attribute is specified, the form controller is published
onto the current scope under this name.
As you are manually also adding a function named addComment, it is using the wrong one when evaluating the ng-submit.

AngularJS - Pass parameters into Controller?

I'm trying to create a simple blog website using AngularJS. I'm just starting out, so what I'm thinking my not be the best way to do this, so any alternative suggestions are welcome.
I have a controller.js file with two blog controllers. One to display a list of blog posts, and the other that displays the post content by including an HTML file.
controller.js
myAppControllers.controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('articles/articles.json').success(function (articles) {
$scope.articles = articles;
});
}]);
myAppControllers.controller('BlogPostCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
$scope.includeFile = 'articles/' + $routeParams.blogPostId + '.html';
}]);
articles.json
[
{
"id": "test-article-one",
"title": "Test Article one",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test summary"
},
{
"id": "test-article-two",
"title": "Test article two",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test for article two"
}
]
app.js
when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl'
}).
when('/blog/:blogPostId', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl'
}).
blog-post.html
<ng-include src="'partials/header.html'"></ng-include>
<!-- Want to add title, author, datePosted information here... -->
<article class="content">
<ng-include src="includeFile"></ng-include>
</article>
This blog listings work fine. When I click into a blog post, it also serves up the content from the HTML file OK as well. However, I want to be able to reuse the title, author and datePosted properties from the selected article in the blog-post.html partial view. What's the best way to do this? Would I need to pass them to the Controller somehow to then pass to the view? I don't really want to pass these as routeParams. Or would I need to do a $http.get on articles.json and iterate through to find the selected article and then pass the property values back to the view?
Thanks for the help.
You said that suggestions are welcome, so here it goes.
1 - Transport all your Blog logic to a service;
2 - Provide the data on resolving routes. This is a better approach to handle errors during the load time, 404s, and so on. You can provide a listener to $routeChangeError and deal with it there;
3 - On the service declared below, you have the methods to call your data and a method to retrieve the list cached on the service:
// services.js
myAppServices
.service('BlogService', ['$http', '$q', function ($http, $q) {
var api = {},
currentData = {
list: [],
article: {}
};
api.getSaved = function () {
return currentData;
};
api.listArticles = function () {
var deferred = $q.defer(),
backup = angular.copy(currentData.list);
$http.get('articles/articles.json')
.then(function (response) {
currentData.list = response;
deferred.resolve(response);
}, function () {
currentData.list = backup;
deferred.reject(reason);
});
return deferred.promise;
};
api.getArticle = function (id) {
var deferred = $q.defer(),
backup = angular.copy(currentData.article),
path = 'articles/' + id + '.html';
$http.get(path, {
cache: true
})
.then(function (response) {
currentData.article = {
path: path,
response: response
};
deferred.resolve(currentData.article);
}, function (reason) {
currentData.article = backup;
deferred.reject(currentData.article);
});
return deferred.promise;
};
return api;
}]);
The BlogService.getSaved() will retrieve the stored data, made after each call.
I've made a method to call the ng-include path too, so you can verify if it exists, with cache === true, the browser will keep a copy of it, when calling it again on the view. A copy of the response of the blog article is made too, so you can access its path and the response whenever you need.
On the controllers below, they were adaptated to supply the current needs:
// controller.js
myAppControllers
.controller('BlogListCtrl', ['$scope', 'articles',
function ($scope, articles) {
$scope.articles = articles;
/* OTHER STUFF HERE */
}
])
.controller('BlogPostCtrl', ['$routeParams', '$scope', 'article' 'BlogService',
function ($routeParams, $scope, article, BlogService) {
// On `article` dependency, you have both the original response
// and the path formed. If you want to use any of it.
$scope.includeFile = article.path;
// To get the current stored data (if any):
$scope.articles = BlogService.getSaved().list;
// Traverse the array to get your current article:
$scope.article = $scope.articles.filter(function (item) {
return item.id === $routeParams.id;
});
/* OTHER STUFF HERE */
}
]);
And the route declarations were changed to load the data when resolving the routes.
// app.js
$routeProvider
.when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl',
resolve: {
articles: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.listArticles();
}]
}
})
.when('/blog/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl',
resolve: {
article: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.getArticle($routeParams.blogPostId);
}]
}
})
This is maybe a common question in angular. What you have to understand is that Scope is defined per controller... In order to share data across controller you still have the option to use $scope.$parent or $rootScope to link controllers but I would use those carefully.
It is better to use Angular Services which are based on singleton patterns therefore you can use them to share information between controllers and I think it will be a better approach.
I found that this has been previously discussed and here are some good examples:
AngularJS Service Passing Data Between Controllers
You can use a global scope to set this data, or you can use service to communicate between the controllers. There is a lot of ways to resolve this problem read a little bit more about services in the link bellow and see if you can find how to resolve your problem.
AngularJS: Service vs provider vs factory

Categories

Resources