one controller for multiple pages - javascript

i maked one website with routes by $routeProvider, i made controller for every page and it looks like:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/category/Web development', {
templateUrl: 'pages/web-dev.html',
controller: 'catCtrl'
})
.when('/category/Game Programming', {
templateUrl: 'pages/game-programming.html',
controller: 'catCtrl2'
})
myApp.controller('catCtrl', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/web-dev")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category" )
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
myApp.controller('catCtrl2', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/game-programming")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category")
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
as you can see, both controllers have same content, but i would like to make only one controller for different pages, any advice how i could make it? i tryed to set same controller in $routeProvider but its not working :(

I think your best approach would be something like this:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/category/:category', {
templateUrl: function (urlattr) {
return '/category/' + urlattr.category + '.html';
},
controller: 'CategoryController',
controllerAs: 'categoryCtrl'
}).otherwise({
redirectTo: '/category/web_development'
});
}]);
myApp.controller('CategoryController', ['$routeParams', '$http', function ($routeParams, $http) {
var categoryCtrl = this;
// Use $http based on $routeParams.category
}]);

Related

Converting Angularjs to Vuejs

I am uplifting a chat application from AngularJS to VueJS and I don't have much clue about how the AngularJS. There isn't really a great resources available on AngularJS right now to gain some insight.
If someone could help me in this I'd really appreciate it.
I wish to convert this below AngularJS code to VueJS completely.
var app = angular.module('IBMfinder', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider, settings) {
$routeProvider
.when('/main', {
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
.when('/find', {
templateUrl: 'find.html',
controller: 'findCtrl',
})
.when('/chat', {
templateUrl: 'chat.html',
controller: 'chatCtrl',
})
.otherwise({
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
}])
app.controller('userCount', ['$scope', 'socket', function($scope,
socket){
socket.on('userCount', function(amount){
$scope.online = amount;
})
}]);
app.controller('welcomeCtrl', ['$scope', '$location', 'settings',
'socket', function($scope, $location, settings, socket){
$scope.users = 13;
if(settings.getUsername()!==""){
socket.emit('delete');
settings.reset();
}
$scope.enter = function(){
settings.setUsername($scope.name);
$location.path('/find');
}
}]);
app.controller('findCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', function($scope, $location, settings,
socket, $rootScope){
$scope.username = settings.getUsername();
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
if(settings.exists){
socket.emit('delete');
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('match', function (data) {
settings.setPartner(data['username'], data['id']);
$location.path('/chat');
});
}]);
app.controller('chatCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', '$timeout', '$window', '$interval',
function($scope, $location, settings, socket, $rootScope, $timeout,
$window, $interval){
var typing = false;
var focus = true;
var titleTimer;
var onFocus = function(){
focus = true;
$interval.cancel(titleTimer);
document.title = 'Chat-Box';
}
var onBlur = function(){
focus = false;
}
$window.onfocus = onFocus;
$window.onblur = onBlur;
$scope.username = settings.getUsername();
$scope.partnerTyping = false;
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('incoming message', function(data){
if($scope.chatlog[$scope.chatlog.length-1]){
if($scope.chatlog[$scope.chatlog.length-1].sentby == data.userID){
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: '',
chatmessage: data.message
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
if(!focus){
document.title = 'New Message!';
$interval.cancel(titleTimer);
titleTimer = $interval(function(){
if(document.title == 'New Message!'){
document.title = 'Chat-Box';
}else{
document.title = 'New Message!';
}
}, 1000)
}
});
socket.on('aborted', function(data){
alert('Your partner left, sorry!');
socket.emit('delete');
settings.reset();
location.href = "index.html";
})
$scope.typing = function(){
if(!typing){
socket.emit('typing', settings.getID());
typing = true;
var stop = $timeout(function() {
typing = false;
socket.emit('stop typing', settings.getID());
}, 2000);
}
}
socket.on('typing', function(data){
$scope.partnerTyping = true;
$('#chatbox').scrollTop(10000);
})
socket.on('stop typing', function(data){
$scope.partnerTyping = false;
$('#chatbox').scrollTop(10000);
})
$scope.sendMessage = function(){
if($scope.message==""){
}else{
socket.emit( 'new message', {
message:$scope.message,
partner:$scope.partner,
partnerID: settings.getID()
});
}
$scope.message = "";
}
$scope.partner = settings.getPartner();
}]);
app.service('settings', function() {
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
this.setExists = function(bool){
this.exists = bool;
}
this.setUsername = function(uname){
this.username = uname;
}
this.getUsername = function(){
return(this.username);
}
this.setUserID = function(id){
this.userdata.id = id;
}
this.getuserdata = function(){
return(this.userdata);
}
this.setPartner = function(uname, id){
this.partner = uname;
this.partnerID = id;
}
this.getPartner = function(){
return(this.partner);
}
this.getID = function(){
return(this.partnerID);
}
this.reset = function(){
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
}
});
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
disconnect: function(id){
socket.disconnect(id);
}
};
});
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
app.directive('schrollBottom', function () {
return {
scope: {
schrollBottom: "="
},
link: function (scope, element) {
scope.$watchCollection('schrollBottom', function (newValue) {
if (newValue)
{
$(element).scrollTop(100000);
}
});
}
}
})
It'd be great if someone could point me to any great resources. I've not had any luck since past week regarding this.
Video Tutorials
https://www.youtube.com/watch?v=i9MHigUZKEM
https://egghead.io/courses/angularjs-fundamentals
Text Tutorials
https://docs.angularjs.org/tutorial
Try to search on google first.
If you can't understand something ask a concrete question with an example (it doesn't have to be the full code) so we can help you better.
I don't know if you have experience with Vue.js, I can tell you worse what those tutorials will explain way better. AngularJS uses a different approach than Vue, Angular 2+ or React.
Those frameworks use a component approach so you divide the app into multiple components that have properties.
Angular use an MVC-ish approach, you define modules with angular. module those modules can have external or core dependencies defined in the array.
A module can have a router, a router will define the views and the controller of each view. The views have angular directives and HTML, and the controllers have the logic.
Use one of those tutorials to learn more.

How do I populate html using angular controller prior to display

I am trying to pre-load data based on ng-controller attributes prior to displaying the html and in turn prior to button click(submit). I am new to angular js and not sure how to accomplish the task.
There will be one question and n number of answer options
May last try is as seen in code but I need to get to the controller other than button click. I need to see the question and possible answers before the html is present.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/angularjs.min.1.7.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-route.min.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/app.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/vote.js"></script>
<!--<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/HomePageVoteController.js"></script>-->
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/vote.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/route.js"></script>
<script>
// app
var app = angular.module('quickSurveyApp', ["ngRoute"]);
// controller(s)
app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
//app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
// app.factory("VoteService", ["$scope", "qa", "$location", function ($scope, qa, $location) {
$scope.activeQuestions = qa.activeQuestions;
$scope.records = qa.records;
$scope.QuestionText = qa[0].QuestionText;
$scope.AnswerText = qa[0].AnswerText;
$scope.Answers = qa[0].Answers;
$scope.error = false;
$scope.AddVote = function () {
$scope.error = !!$scope.answer;
}
}]);
// service(s)
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
res.setHeader('Access-Control-Allow-Origin', '*');
var service = {};
//Gets all data for page.
var questionNumber = 0;
service.pageInit = function () {
var deferred = $q.defer();
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);
// route(s)
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick Survey/survey.html",
//controller: "VoteCtrl",
controller: "VoteCtrl",
// it's is good to download the data before displaying the template without the data
// so all we found in resolve is gonna be "resolved" before display the page and running the controller
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
return VoteService.pageInit();
}]
}
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
<body ng-app="quickSurveyApp">
<div>
<h1>Quick Survey</h1>
<div ng-view></div>
</div>
</body>
</html>
var app = angular.module("quickSurveyApp", ["ng-Route"]);
app.config(["$routeProvider", function ($routeProvider) {
//res.setHeader('Access-Control-Allow-Origin', '*');
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick-Survey/survey.html",
//templateUrl: "/API/quick-survey/api-test-pages/Quick Survey/survey.html",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
// return VoteService.pageInit(1);
return VoteService.pageInit();
}]
}
})
.when("/question/:q", {
templateUrl: "templates/survey.tpl",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
var questionNumberFromURL = $route.current.params.q;
//return VoteService.pageInit(questionNumberFromURL);
return VoteService.pageInit();
}]
}
})
.when("/thanks", {
templateUrl: "templates/home.tpl",
controller: ["$timeout", "$scope", "$location", function ($timeout, $scope, $location) {
$scope.message = "Thank you !!!";
$timeout(function () {
$location.path("/");
}, 3000);
}]
}).
otherwise({
redirectTo: '/xxxx.html'
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Timothy+Mruk&id=13332&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
app.controller("VoteCtrl", function ($scope, $http) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
//Gets all data for page.
$scope.pageInit = function () {
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsbyZone/0'
//*url: 'http://localhost:51230/api/Question/GetQuestionsByZone/0'
}).then(function (response){
$scope.activeQuestions = response.data;
},function (error){
console.log(error);
});
};
// inserts new request
$scope.insertRequest = function () {
$http.post("/API/quick-survey/api/Vote/AddVote", $scope.voteRequest).then(function (data, status, headers, config) {
alert("success");
}, function (data, status, headers, config) {
console.log("error!");
console.log(data);
});
};
// checks if user already voted for a question
$scope.getUserVoteCount = function () {
// get true or false
$http.get("/API/quick-survey/api/Vote/GetUserVoteCount/866/ijohnson/0").success(function (data, status, headers, config) {
$scope.activeQuestions = data;
}).error(function (data, status, headers, config) {
console.log(status);
});
};
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
app.controller("VoteCtrl", ["$scope","qa","$location", function ($scope, qa, $location) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
$scope.activeQuestions = qa.activeQuestions;
//*******
$scope.Answers = qa.records;
$scope.error = false;
$scope.AddVote = function () {
if ($scope.answer == undefined)
$scope.error = true;
else {
$scope.error = false;
if (qa.next)
$location.path("question/" + qa.next)
else
$location.path("thanks");
}
}
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=22665&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
}]);
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
var service = {};
var urlBase = "API/quick-survey/api";
$scope.pageInit = function () {
// Get Questions from api
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsByZone/0'
}).then(function (response) {
$scope.activeQuestions = response.data;
}, function (error) {
console.log(error);
});
};
//Gets all data for page.
service.pageInit = function () {
var deferred = $q.defer();
//res.setHeader('Access-Control-Allow-Origin', '*');
//$http.get(urlBase + '/Question/GetQuestionsByZone/' + questionNumber).then(function (response) {
// $http.get(urlBase + '/Question/GetQuestionsByZone/' + 0).then(function (response) {
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// inserts new request
service.insertRequest = function (questionNumber) {
var deferred = $q.defer();
$http.post(urlBase + '/Vote/AddVote', $scope.voteRequest).then(function (response, status, headers, config) {
console.log(response.data);
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// checks if user already voted for a question
service.getUserVoteCount = function (questionNumber) {
var deferred = $q.defer();
// get true or false
$http.get(urlBase + '/Vote/GetUserVoteCount/866/ijohnson/' + questionNumber).success(function (response, status, headers, config) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);// JavaScript source code
h1>Quick Survey</h1>
<div ng-model="QuestionText">
<!--Question-->
<h2>{{QuestionText}}</h2>
</div>
<!-- <div -->
<div ng-model="AnswerText">
<!--Possible Answers-->
<br ng-repeat-start="a in Answers" />
<input id="button{{a.AnswerText}}" name="selection" value="{{a.AnswerText}}" type="radio" ng-model="$parent.Answer" />
<label for="button{{a.AnswerText}}" ng-repeat-end>{{a.AnswerText}}</label>
</div>
<br />
<br />
<div>
<input id="surveybtn" type="button" value="Vote Now" ng-click="AddVote()" />
</div>

AngularJS update function is (still)not working

I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}

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);

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;

Categories

Resources