Issue with passing values through state.go - javascript

I'm having trouble passing through a uid into the $state.go function.
Here is my controller:
.controller('chatCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory,$stateParams) {
$scope.data = {};
$scope.session_id= sessionStorage.getItem('session_id');
var sid = $scope.session_id;
if($scope.session_id == null){
$state.go('login');
}
else {
var cload = 'https://m.socialnetwk.com/home/app/chat_load.php';
$http.post(cload, {id : $scope.session_id}).then(function (res){
$scope.chat = res.data;
});
$scope.chat = {};
$scope.openModal = function(id) {
$scope.selectedId = id;
$state.go('chat2',{uid: $scope.selectedId});
}
}
})
.controller('chat2Ctrl', function($scope,$http,$ionicPopup,$state,$ionicHistory,$stateParams) {
$scope.data = {};
$scope.id = {};
$scope.session_id= sessionStorage.getItem('session_id');
var sid = $scope.session_id;
if($scope.session_id == null){
$state.go('login');
}
else {
var pmloaddd = 'https://m.socialnetwk.com/home/app/upml.php';
$http.post(pmloaddd, {id : $state.params.uid}).then(function (res){
$scope.pmload = res.data;
});
}
})
Here is my app.js:
$stateProvider
.state('chat2', {
url: '/page9',
params: {
uid: null
},
templateUrl: 'templates/chat2.html',
controller: 'chat2Ctrl'
})

There are two mistakes
Did not add the parameter to the URL property of your state configuration
And $state.params.uid is invalid.
Use the below solution.
Your app.js
$stateProvider
.state('chat2', {
url: '/page9/:uid', //added the parameter here
params: {
uid: null
},
templateUrl: 'templates/chat2.html',
controller: 'chat2Ctrl'
})
Your else part of the Chat2 controller should be as below
if($scope.session_id == null){
$state.go('login');
}
else {
var pmloaddd = 'https://m.socialnetwk.com/home/app/upml.php';
// modified the below line
$http.post(pmloaddd, {id : $stateParams.uid}).then(function (res){
$scope.pmload = res.data;
});
LIVE DEMO

First you need to pass it with url and then you can access it like--
$stateParams.
$stateProvider
.state('chat2', {
url: '/page9/:uid',
controller:'name of yout controller',
controller: function($stateParams){
$stateParams.uid //*** Exists! ***//
}
});
then you can access like this:-
$stateparams.uid at controller.
You can also refer this link--Url routing--stateParams Service

Related

Error in linking page

I had a Problem in linking pages. Suppose, After Login from URL "/admin_1_angularjs/login.html",
the dashboard.html page should be Appear from this URL "/admin_1_angularjs/#/dashboard.html". instead it appeared in "/admin_1_angularjs/#/login.html" link. How do i fix this? here is my angularJS Controller...
MetronicApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
// Redirect any unmatched url
$urlRouterProvider.otherwise("/login.html");
app.version = '1454574448';
$stateProvider.state('login', {
url: "/login.html",
templateUrl: 'login.html?_=' + app.version,
controller: 'login'
})
.state('dashboard', {
url:"/dashboard.html",
templateUrl: 'views/profile/dashboard.html?_=' + app.version,
controller: 'dashboard'
})
this is my login controller.
var app = angular.module('myApp', []);
app.controller('login', ['$window','$scope','$timeout', function ($window,$scope,$timeout) {
$scope.hasError = false;
$scope.errorMessage = "";
$scope.input = {
username: '',
password: ''
};
$scope.counter = 0;
$scope.isLoading = false;
$scope.setError = function (hasError) {
$scope.hasError = hasError;
};
$scope.login = function () {
$scope.isLoading = true;
var postData = {
clazz: "com.smk.aps.server.model.rpc.request.RPCAdminLogin",
signature: "",
data: {
// requestLoginID: app.uuid.v4(),
// requestUsername: $scope.input.username,
// requestPassword: CryptoJS.SHA1($scope.input.password).toString()
}
};
postData.data._class = postData.clazz;
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError = true) {
if($scope.counter == 0) {
$scope.errorMessage = "Invalid username or password. Error code = " + $scope.counter;
console.log($scope.errorMessage);
$scope.counter++;
} else if ($scope.counter == 1) {
$scope.errorMessage = "Server busy please try again later. Error code = " + $scope.counter;
console.log($scope.errorMessage);
$scope.counter++;
} else {
$window.location.href = "/admin_1_angularjs/";
}
}
}, 2000);
You have to set HTML5 mode to true to get desired result. Please refer to HTML5Mode section of following link for more details.
https://docs.angularjs.org/guide/$location

Angular JS routing not working

I am trying to route my page to another page once the controller is accessed but its not working. I can route the first two pages but the third one is not working. Can someone help me on this.
This is my routing code:
$routeProvider', function ($routeProvider) {
$routeProvider.
when('/category', {
//templateUrl : 'js/partials/course-list.html',
controller : 'CategoryController'
}).
when('/category/:categoryid', {
templateUrl : 'js/partials/film-list.html',
controller : 'MovieController'
}).
when('/actor/:filmid', {
templateUrl : 'js/partials/actor-list.html',
controller : 'ActorController'
}).
otherwise({
redirectTo : '/'
});
}
Currently my ActorController is not working. Once i click on the movies it should show the actor of the films but in my case its not working
This is my partial html file for the movie-list.html
<section>
<h3>{{movieCount}}</h3>
<table>
<tr data-ng-repeat="movie in movies" data-ng-click="selectFilm($event,movie)" style="cursor: pointer;">
<td>{{movie.title}}</td>
</tr>
<strong>{{successMessage}}</strong>
</table>
And this is my controller code
).controller('ActorController',
[
'$scope',
'dataService',
'$routeParams',
function ($scope, dataService, $routeParams){
$scope.actors = [ ];
$scope.actorCount = 0;
var getActors = function (moviecode) {
dataService.getActors(moviecode).then(
function (response) {
$scope.actorCount = response.rowCount + ' actors';
$scope.actors = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "Actor Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
// only if there has been a courseid passed in do we bother trying to get the students
if ($routeParams && $routeParams.filmid) {
console.log($routeParams.filmid);
getActors($routeParams.filmid);
}
}
]
)
This is the selectFilm() code from the MovieController
$scope.selectedFilm = {};
$scope.selectFilm = function ($event,movie) {
$scope.selectedFilm = movie;
$location.path('/actor/' + movie.film_id);
}
This is the movie controller code
).controller('MovieController',
[
'$scope',
'dataService',
'$routeParams',
'$location',
function ($scope, dataService, $routeParams, $location){
$scope.movies = [ ];
$scope.movieCount = 0;
var getMovies = function (moviecode) {
dataService.getMovies(moviecode).then(
function (response) {
$scope.movieCount = response.rowCount + ' movies';
$scope.movies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "Movies Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
$scope.selectedFilm = {};
$scope.selectFilm = function ($event,movie) {
$scope.selectedFilm = movie;
$location.path('/actor/' + movie.film_id);
// $window.location.href = '/actor/' + movie.film_id
console.log(movie.film_id);
}
// only if there has been a courseid passed in do we bother trying to get the students
if ($routeParams && $routeParams.categoryid) {
console.log($routeParams.categoryid);
getMovies($routeParams.categoryid);
}
}
]
)
I solved the problem by myself wher first of all the $location variable was not defined in the function and later on the movie object dont have the film_id so I had to readjust my SQL query to make it work. After changing the SQL query i can route my page now.

Angular extract array from expected object response

I am working with wordpress' rest api and I am extracting a list of posts which allow the user to see a single post. Now I want to include the comments as well but I cannot wrap my head around this. I am using a factory for the calls:
.factory('Articles', function ($http) {
var articles = [];
storageKey = "articles";
function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}
return {
all: function () {
return $http.get("http://www.examplesite.com/tna_wp/wp-json/posts?filter[category_name]=test").then(function (response) {
articles = response.data;
console.log(response.data);
return articles;
});
},
get: function (articleId) {
if (!articles.length)
_getCache();
for (var i = 0; i < articles.length; i++) {
if (parseInt(articles[i].ID) === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
})
My controller:
.controller('ExampleCtrl', function ($scope, $stateParams, _, Articles) {
$scope.articles = [];
Articles.all().then(function (response){
$scope.articles = response;
window.localStorage.setItem("articles", JSON.stringify(response));
},
function (err) {
if(window.localStorage.getItem("articles") !== undefined) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
}
}
);
$scope.doRefresh = function() {
Articles.all().then(function (articles){
var loadedIds = _.pluck($scope.articles, 'id');
var newItems = _.reject(articles, function (item){
return _.contains(loadedIds, item.id);
});
$scope.articles = newItems.concat($scope.articles);
$scope.$broadcast('scroll.refreshComplete');
});
};
})
//THIS IS WHERE I AM TRYING AND FAILING
.controller('ExampleInnerCtrl', function ($http, $scope, $stateParams, $cordovaSocialSharing, $ionicModal, Articles) {
$scope.article = Articles.get($stateParams.articleId);
var url = Articles.get($stateParams.articleId);
$scope.comments = [];
$http.get("http://www.example.com/tna_wp/wp-json/posts/" +url+ "/comments").then(function (response, commentId) {
$scope.comments = response.data;
console.log(response.data);
return $scope.comments;
});
$scope.comment = $stateParams.commentId;
$ionicModal.fromTemplateUrl('gauteng-comments.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.sharePost = function(link){
window.plugins.socialsharing.share('I just read this article on The New engage: ', null, null, "http://example.com" + link);
};
})
now in the controller if I include the post id manually I can get the comments for that post, however I cannot seem to store that post ID in a variable to use
--------EDIT
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: "NavCtrl"
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "templates/home.html"
}
}
})
.state('app.provinces', {
url: "/provinces",
views: {
'menuContent': {
templateUrl: "templates/provinces.html"
}
}
})
.state('app.example', {
url: "/provinces/example",
views: {
'menuContent': {
templateUrl: "templates/example.html",
controller: "ExampleCtrl"
}
}
})
.state('app.exampleSingle', {
url: "/provinces/example/:articleId",
views: {
'menuContent': {
templateUrl: "templates/exampleSingle.html",
controller: "ExampleInnerCtrl"
}
}
})
;
$urlRouterProvider.otherwise("/app/home");
});
Ok it was my stupidity... I just stored the variable as: var url = $scope.article.ID;

ionic : Master Detail returns only id

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

angular injector with asp.net Boilerplate not working

I'm trying to use the Angular injection come with asp.net Boilerplate,
I'm following the "tutorial" from here http://www.codeproject.com/Articles/791740/Using-AngularJs-ASP-NET-MVC-Web-API-and-EntityFram#ArticleBuildWebApiServices
to get started with my project, for now I want to load the Tasks as Parts
but for some reason I get the following error:
Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=os.views.part.list&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native)
at http://localhost:6234/Scripts/angular.min.js:6:416
at Nb (http://localhost:6234/Scripts/angular.min.js:19:417)
at ob (http://localhost:6234/Scripts/angular.min.js:20:1)
at $get (http://localhost:6234/Scripts/angular.min.js:75:177)
at http://localhost:6234/Scripts/angular.min.js:57:112
at r (http://localhost:6234/Scripts/angular.min.js:7:408)
at I (http://localhost:6234/Scripts/angular.min.js:56:496)
at g (http://localhost:6234/Scripts/angular.min.js:51:299)
at http://localhost:6234/Scripts/angular.min.js:50:414
the application is a SPA.
the Main app is loaded here:
(function() {
"use strict";
var app = angular.module("app", [
"ngAnimate",
"ngSanitize",
"ui.router",
"ui.bootstrap",
"ui.jq",
"abp"
]);
//Configuration for Angular UI routing.
app.config([
"$stateProvider", "$urlRouterProvider",
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: "/App/Main/views/home/home.cshtml",
menu: "Home" //Matches to name of 'Home' menu in OnderdelenshopNavigationProvider
})
.state("about", {
url: "/about",
templateUrl: "/App/Main/views/about/about.cshtml",
menu: "About" //Matches to name of 'About' menu in OnderdelenshopNavigationProvider
})
.state("listParts", {
url: "/list",
templateUrl: "/App/Main/views/parts/list.cshtml",
menu: "ListParts"
});
}
]);
})();
then when routed to /list the following JS is loaded:
(function() {
var app = angular.module("app");
var controllerId = "os.views.parts.list";
app.controller(controllerId, [
'$scope', 'abp.services.tasksystem.part',
function($scope, partService) {
var vm = this;
vm.localize = abp.localization.getSource("Onderdelenshop");
vm.parts = [];
$scope.selectedTaskState = 0;
$scope.$watch("selectedPartState", function(value) {
vm.refreshParts();
});
vm.refreshParts = function () {
console.log("test");
abp.ui.setBusy( //Set whole page busy until getTasks complete
null,
partService.getParts({ //Call application service method directly from javascript
state: $scope.selectedPartState > 0 ? $scope.selectedPartState : null
}).success(function (data) {
console.log("hey");
vm.parts = data.parts;
})
);
};
vm.changePartState = function(part) {
var newState;
if (part.state === 1) {
newState = 2; //Completed
} else {
newState = 1; //Active
}
partService.updatePart({
partId: part.id,
state: newState
}).success(function() {
part.state = newState;
abp.notify.info(vm.localize("TaskUpdatedMessage"));
});
};
vm.getPartCountText = function() {
return abp.utils.formatString(vm.localize("Xparts"), vm.parts.length);
};
}
]);
})();
this is the http://localhost:6234/api/AbpServiceProxies/GetAll?type=angular
(function (abp, angular) {
if (!angular) {
return;
}
var abpModule = angular.module('abp');
abpModule.factory('abp.services.tasksystem.person', [
'$http', function ($http) {
return new function () {
this.getAllPeople = function (httpParams) {
return $http(angular.extend({
abp: true,
url: abp.appPath + 'api/services/tasksystem/person/GetAllPeople',
method: 'POST',
data: JSON.stringify({})
}, httpParams));
};
};
}
]);
})((abp || (abp = {})), (angular || undefined));
(function (abp, angular) {
if (!angular) {
return;
}
var abpModule = angular.module('abp');
abpModule.factory('abp.services.tasksystem.task', [
'$http', function ($http) {
return new function () {
this.getTasks = function (input, httpParams) {
return $http(angular.extend({
abp: true,
url: abp.appPath + 'api/services/tasksystem/task/GetTasks',
method: 'POST',
data: JSON.stringify(input)
}, httpParams));
};
this.updateTask = function (input, httpParams) {
return $http(angular.extend({
abp: true,
url: abp.appPath + 'api/services/tasksystem/task/UpdateTask',
method: 'POST',
data: JSON.stringify(input)
}, httpParams));
};
this.createTask = function (input, httpParams) {
return $http(angular.extend({
abp: true,
url: abp.appPath + 'api/services/tasksystem/task/CreateTask',
method: 'POST',
data: JSON.stringify(input)
}, httpParams));
};
};
}
]);
})((abp || (abp = {})), (angular || undefined));
Any ideas what I might be forgetting?
Update 1: Got further; the controller definition must be like this:
app.controller(controllerId, [
'$scope', '$location', 'abp.services.tasksystem.part',
function ($scope, $location, partService) { ... }
Now getting internal error though, trying to fix that
I was wondering where are you getting the abp in the controller. You need to inject it

Categories

Resources