AngularJS Pass data to view - javascript

I have a controller that is as follows:
angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {
$scope.selectedCourse = [];
$scope.getCourse = function(id){
Course.getCourse(id)
.then(function(response) {
$scope.selectedCourse = {
course_name : response.data.data['name'],
course_code : response.data.data['code']
}
$location.path('/course');
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
});
With view as follows:
<div class="ten wide column" ng-controller="CoursesCtrl">
<h2 class="ui header">
{{selectedCourse.course_name}}
</h2>
<h4 class="ui header">
Instructor: {{selectedCourse.course_code}}
</h4>
</div>
I am unable to pass the data into the view which has the location path: course:
Looking closely in the code, is there something that has been left out or needs to be considered.

Because you have written code for selectedCourse in getCourse function so you have to write selectedCourse outside getCourse function.

angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {
$scope.selectedCourse ={}; //here was the mistake
$scope.getCourse = function(id){
Course.getCourse(id)
.then(function(response) {
$scope.selectedCourse = {
course_name : response.data.data['name'],
course_code : response.data.data['code']
}
$location.path('/course');
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
});

In your code $scope.selectedCourse is declared as array. declare it as an object for your purpose as $scope.selectedCourse = {};
angular.module('myApp').controller('CoursesCtrl', function ($scope, $auth, $location, toastr, Course, $http) {
//Loading the value based on the existance in parent controller.
$scope.selectedCourse = ($scope.$parent.selectedCourseData)? $scope.$parent.selectedCourseData: {};
$scope.getCourse = function (id) {
Course.getCourse(id)
.then(function (response) {
$scope.selectedCourse = {
course_name: response.data.data['name'],
course_code: response.data.data['code']
}
//Keeping the value in a parent controller
$scope.$parent.selectedCourseData = $scope.selectedCourse;
$location.path('/course');
})
.catch(function (response) {
toastr.error(response.data.message, response.status);
});
};
});

Related

Angular load data from server and display information on separate page

I have a page where I display all usernames. Now I want to click on one of these usernames make a call to server to retrieve more information and display it on separate User page. (First name, last name, etc)
My problem is that when I click on username page opens but fields are not populated. Could you please review my code and suggest what I am doing wrong there?
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "pages/login_page.html"
})
.when("/userpage", {
controller : 'UserController',
templateUrl : "pages/user_page.html"
})
.when("/allusers", {
controller : 'AllUserController',
templateUrl : "pages/all_users.html"
});
});
This is my login code. After user authenticated it can see all other users. So I am changing view to #allusers
app.directive("loginForm", function (AuthorizedHttp, ConfigurationRepository, UserObj) {
return {
restrict: 'E',
scope: {
},
templateUrl: 'templates/login-template.html',
replace: 'true',
controller: ['$scope', '$http', '$window',
function($scope, $location, $window) {
$scope.loginError = false;
$scope.login = function () {
$scope.loginError = false;
UserObj.setState(null, null, $scope.username, $scope.password, null);
AuthorizedHttp.get('http://{0}/account/user/login'.format(ConfigurationRepository.getBackendHostName()))
.success(function (response) {
UserObj.setState(response.first_name, response.last_name, response.email, $scope.password, response.role, response.timezones);
$window.location = "#allusers";
})
.error(function (err, status) {
$scope.username = '';
$scope.password = '';
$scope.loginError = true;
})
}
}
]
}
});
Code below responsible to make a call and retrieve all users. Works fine.
app.controller('AllUserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService) {
$scope.init = function () {
TimezoneService.getAllUsers()
.success(function (response) {
$scope.users_emails = response.map(function (item) {return item.email})
})
.error(function (err, status) {
alert('Error loading all users ')
});
};
});
HTML to display all usernames. Also set ng-click to pass a username as parameter to retrieve required user.
<div ng-controller="AllUserController" ng-init="init()">
<div ng-controller="UserController">
<div ng-repeat="email in users_emails" class="item-unchecked">
<a ng-click="getUser(email)">{{email}}</a>
</div>
</div>
</div>
User controller. Executed every time I click on username link.
app.controller('UserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService, $window) {
$scope.user_display_name = 'Now set yet';
$scope.getUser = function(username) {
TimezoneService.getUser(username)
.then(function (response) {
$scope.required_user = response.data;
$scope.user_display_name = '{0} ({1})'.format(response.data.first_name, response.data.email);
$scope.user_timezones = response.data.timezones.map(function (item) {
return item.timezone_name
});
$scope.user_role = response.data.role;
$window.location = '#userpage';
});
};
});
As a result user_page.html is loaded but all fields are not set. I don't understand why since I am setting a scope value before I change a $window.location.
Remove ng-controller="UserController" from your HTML
Create a function in your AllUserController like that
$scope.customNavigate = function(routeToNavigate, routeParameter){
$location.path("/" + routeToNavigate + "/" + routeParameter);
}
Change .when("/userpage", { to .when("/userpage/:email", {
Change ng-click="getUser(email)" to ng-click="customNavigate("userpage", email)"
Inject $routeParams to your UserController
Change $scope.getUser = function(username) { to function getUser (username) {
Call getUser($routeParams.email) in your UserController.

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.

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

$http.post from angular form not sending any data

I have a form that is posting /api/tradelink but it doesn't send any body or data with it.
HTML :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Services :
.factory('Auth', ['$http', '$api', '$window', function ($http, $api, $window) {
var authFactory = {};
authFactory.authenticate = function(){
$http.post($api.url + 'auth')
.successs(function(url){
$window.location.href = url;
});
};
authFactory.send = function () {
return $http.post($api.url + 'tradelink');
};
return authFactory;
}]);
Controller ;
.controller('AppCtrl', ['$scope', 'Auth', '$location', '$cookies', function ($scope, Auth, $location, $cookies) {
var sidTemp = 'needtomakeitanewvalue';
$scope.checklogin = function () {
$scope.sid = $cookies.get('sid2');
console.log($scope.sid);
}
$scope.sendTradelink = function () {
Auth.send($scope.tradelink)
.success(function (res) {
$scope.sidTemp = 'needtomakeitanewvalue';
$cookies.put('sid2', sidTemp);
$location.path('/');
});
}
$scope.auth = function () {
Auth.authenticate();
}
}])
Server side holding api request, nothing inside req.body or req.params. Both show as empty objects.
api.post('/tradelink', function(req, res){
console.log(req.user.steamId);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
Check the Angular docs for $http.post
You are calling Auth.send($scope.tradelink), but your authFactory.send() function needs to accept this tradelink value and then be used as a data param to $http.post()
So:
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelinkId: tradelink });
};

Angular RouteParams send ID

I am trying to send an ID through to a controller using $routeParams via a factory but it is not working.
My $routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl'
});
My factory:
myApp.factory('eventRepo', ['$http', function($http) {
var urlBase = 'php/api.php';
var eventRepo = {};
eventRepo.getEvent = function (id) {
return $http.get(urlBase + '?eventID=' + id);
};
return eventRepo;
}]);
My Controller:
myApp.controller('eventPageCtrl', ['$scope', '$routeParams', 'eventRepo',
function ($scope, $routeParams, eventRepo) {
$scope.getEvent = function (id) {
eventRepo.getEvent($routeParams.eventId)
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
When handling $http.get() inside the controller and not with the factory it works fine so I think I am not passing my $routeParams correctly? Perhaps this line is causing the issue eventRepo.getEvent($routeParams.eventId)?
This works currently, but trying to use $http.get() outside the controller:
myApp.controller('eventPageCtrl', function($scope, $http, $routeParams) {
$http.get("php/api.php?eventID="+$routeParams.eventId).success(function(data){
$scope.eventsDetail = data;
});
});
how about using resolve in your routeProver and returning the eventId and then injecting it in the controller .. example :
$routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl',
resolve : {
eventId: function($route, $location) {
var eventId = $route.current.params.eventId;
return eventId;
});
Controller:
myApp.controller('eventPageCtrl', ['$scope', 'eventId', 'eventRepo',
function ($scope, eventId, eventRepo) { //add it as a dependency
$scope.eventId = eventId; //you can check this to see if its being assigned
$scope.getEvent = function (eventId) { //Edit: eventId added here
eventRepo.getEvent(eventId) //Edit: eventId passed
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);

Categories

Resources