Multi-View Form AngularJS reroute - javascript

I have been experimenting with a few ways to create this form.
Scotch seemed to have a great tutorial with nested views.
This is the part of the JS file I assume the problems occur.
I created a demo at http://plnkr.co/edit/nNTEI4tBw0XFana1nKIS?p=preview.
.controller('formController', function($scope) {
// we will store all of our form data in this object
$scope.formData = {};
// function to process the form
$scope.processForm = function() {
if ($scope.formData = '"phone":"iphone' &&'"type":"xbox"'){
parent.location='results';
}
};
});
How do I get the submit button to reroute to the results.html?
(I wouldn't be surprised if my JS was less than pristine)
any help would be awesome.

Two things that need to be done. First, if you examine your $scope.formData object, you can see that it has two properties for phone and type, so the way you were checking for that in the if block was not correct. Here are the controller changes:
.controller('formController', function($scope, $location) {
// we will store all of our form data in this object
$scope.formData = {};
// function to process the form
$scope.processForm = function() {
if ($scope.formData.phone == 'iphone' && $scope.formData.type == 'xbox'){
$location.path('/results');
}
};
});
Next, routes had to be configured for the results route. Just needed to add this in your route configuration:
.state('results', {
url: '/results',
templateUrl: 'results.html'
});
Here is a forked Plunker: http://plnkr.co/edit/GUpNMRPU0YqfOcveB0nP?p=preview

Related

How store $http get response in variable accesible from outside $http function (Angularjs)?

I'm still learning angular and javascript and I find stack
overflow really helpful. Actually this is first time I couldn't find solution to my problem in other questions & answers here. I tried many solutions, but nothing is working for me.
In short: I want to save response from $http get (user data) in variable, so I could use it in other functions in this controller.
My factory with $http get function:
app.factory('getUserFactory', ['$http', function($http){
return {
getUserData : function(email, password) {
return $http.get('https://xxxxxxx.xxx.xx/api/v1/user/', {
headers: {
"Authorization": 'Basic '+ window.btoa(email +':'+password)
}
});
}
};
}]);
My controller with functions:
app.controller('UserController', ['$scope','$http', 'getUserFactory', function($scope, $http, getUserFactory) {
var user= {}; //Used to bind input fields from html file
$scope.user= user;
$scope.userData = {}; // <-- HERE I WANT TO STORE RESPONSE
$scope.logIn = function() { // function runs on click
getUserFactory.getUserData(user.email, user.password).success(function(response){
$scope.userData = response.objects[0];
});
};
And simple on click function I use to test if it's working:
$scope.consoleLog = function () {
console.log($scope.userData);
};
I assume my problem is connected with asynchrony of javascript, but I always call $http get first (user clicks 'log in' button) and then I try to use response to display user details. But outside $scope.logIn(), $scope.userData becomes an empty object again.
I assume you are calling login method in onclick.just try this:;
$scope.logIn = function() { // function runs on click
getUserFactory.getUserData(user.email, user.password).then(function(response){
$scope.userData = response.objects[0];
});
};

Angular - Best practice for retrieving data from a Factory method

I'm looking for some information on the best way to retrieve data from a local JSON file and handle the response. After browsing through Stack Overflow, I have some mixed thoughts as I've seen multiple ways of doing the same thing (although no explanation on why one may or may not be preferred).
Essentially, I have an Angular app that is utilising a factory to retrieve data from a JSON file; I'm then waiting for the response to resolve in my controller before using it in my html file, similar to the below:
Option 1
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile);
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response.data;
});
}]);
My main point of contention is figuring out when it's best to wait for the response to resolve, or if it even matters. I'm toying with the idea of having the factory return the fulfilled promise, and wait for the controller to retrieve the data also. In my view, it's best to abstract all data retrieval out of the controller and into the factory, but I'm not sure if this extends to waiting for the actual data to be returned within the factory itself. With this in mind, I'm confused about whether to opt for option 1 or option 2 and would really appreciate some feedback from more experienced/qualified developers!
Option 2
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile).then(function(response) {
return response.data;
});
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response;
});
}]);
Thank you for any input/suggestions in advance!
It depends on what your controller is expecting and how you set up your application. Generally, I always go with the second option. Its because I usually have global error or success handlers in all api requests and I have a shared api service. Something like below.
var app = angular.module('app', []);
app.service('ApiService', ['$http', function($http) {
var get = function(url, params) {
$http.get(url, { params: params })
.then(handleSuccess, handleError);
};
// handle your global errors here
// implementation will vary based upon how you handle error
var handleError = function(response) {
return $q.reject(response);
};
// handle your success here
// you can return response.data or response based upon what you want
var handleSuccess = function(response) {
return response.data;
};
}]);
app.service('InfoService', ['ApiService', function(ApiService) {
var retrieveInfo = function() {
return ApiService.get(retrievalFile);
/**
// or return custom object that your controller is expecting
return ApiService.get.then(function(data) {
return new Person(data);
});
**//
};
// I prefer returning public functions this way
// as I can just scroll down to the bottom of service
// to see all public functions at one place rather than
// to scroll through the large file
return { retrieveInfo: retrieveInfo };
}]);
app.controller('InfoController', ['InfoService', function(InfoService) {
InfoService.retrieveInfo().then(function(info) {
$scope.info = info;
});
}])
Or if you are using router you can resolve the data into the controller. Both ngRouter and uiRouter support resolves:
$stateProvider.state({
name: 'info',
url: '/info',
controller: 'InfoController',
template: 'some template',
resolve: {
// this injects a variable called info in your controller
// with a resolved promise that you return here
info: ['InfoService', function(InfoService) {
return InfoService.retrieveInfo();
}]
}
});
// and your controller will be like
// much cleaner right
app.controller('InfoController', ['info', function(info) {
$scope.info = info;
}]);
It's really just preference. I like to think of it in terms of API. What is the API you want to expose? Do you want your controller to receive the entire response or do you want your controller to just have the data the response wraps? If you're only ever going to use response.data then option 2 works great as you never have to deal with anything but the data you're interested in.
A good example is the app we just wrote where I work. We have two apps: a back-end API and our front-end Angular application. We created an API wrapper service in the front-end application. In the service itself we place a .catch for any of the API endpoints that have documented error codes (we used Swagger to document and define our API). In that .catch we handle those error codes and return a proper error. When our controllers/directives consume the service they get back a much stricter set of data. If an error occurs then the UI is usually safe to just display the error message sent from the wrapper service and won't have to worry about looking at error codes.
Likewise for successful responses we do much of what you're doing in option 2. In many cases we refine the data down to what is minimally useful in the actual app. In this way we keep a lot of the data churning and formatting in the service and the rest of the app has a lot less to do. For instance, if we need to create an object based on that data we'll just do that in return the object to the promise chain so that controllers aren't doing that all over the place.
I would choose option two, as it your options are really mostly the same. But let see when we add a model structure like a Person suppose.
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile).then(function(response) {
//we will return a Person...
var data = response.data;
return new Person(data.name, data.age, data.gender);
});
}
}
}]);
This is really simple, but if you have to map more complex data into object models (you retrieve a list of people with their own items... etc), that's when things get more complicated, you will probably want to add a service to handle the mapping between data and models. Well you have another service DataMapper(example), if you choose your first option you will have to inject DataMapper into your controller and you will have to make your request through your factory, and map the response with the injected service. And then you probably say, Should I have all this code here? ... Well probably no.
That is an hypothetical case, something that count a lot is how you feel structuring your code, won't architecture it in a way you won't understand. And at the end take a look at this: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design) and research more information about this principles but focused to javascript.
Good question. A couple of points:
Controllers should be view centric versus data centric therefore you
want remove data logic from the controller and rather have it focus
on business logic.
Models (M in MVC) are a data representation of your application and
will house the data logic. In Angular case this would be a service
or factory class as you rightfully pointed out. Why is that well for
example:
2.1 AccountsController (might have multiple data models injected)
2.1.1 UserModel
2.1.2 AuthModel
2.1.3 SubscriptionModel
2.1.4 SettingsModel
There are numerous ways to approach the data model approach, but I would say your service class should be the data REST model i.e. getting, storing, caching, validating, etc. I've included a basic example, but suggest you investigate JavaScript OOP as that will help point you in the right direction as to how to build data models, collections, etc.
Below is an example of service class to manage your data.Note I have not tested this code but it should give you a start.
EXAMPLE:
(function () {
'use strict';
ArticleController.$inject = ['$scope', 'Article'];
function ArticleController($scope, Article) {
var vm = this,
getArticles = function () {
return Article.getArticles()
.then(function (result) {
if (result) {
return vm.articles = result;
}
});
};
vm.getArticles = getArticles;
vm.articles = {};
// OR replace vm.articles with $scope if you prefer e.g.
$scope.articles = {};
$scope.userNgClickToInit = function () {
vm.getArticles();
};
// OR an init on document ready
// BUT to honest I would put all init logic in service class so all in calling is init in ctrl and model does the rest
function initArticles() {
vm.getArticles();
// OR chain
vm.getArticles()
.then(getCategories); // doesn't here, just an example
}
initArticles();
}
ArticleModel.$inject = ['$scope', '$http', '$q'];
function ArticleModel($scope, $http, $q) {
var model = this,
URLS = {
FETCH: 'data/articles.json'
},
articles;
function extract(result) {
return result.data;
}
function cacheArticles(result) {
articles = extract(result);
return articles;
}
function findArticle(id) {
return _.find(articles, function (article) {
return article.id === parseInt(id, 10);
})
}
model.getArticles = function () {
return (articles) ? $q.when(articles) : $http.get(URLS.FETCH).then(cacheArticles);
};
model.getArticleById = function (id) {
var deferred = $q.defer();
if (articles) {
deferred.resolve(findArticle(id))
} else {
model.getBookmarks().then(function () {
deferred.resolve(findArticle(id))
})
}
return deferred.promise;
};
model.createArticle = function (article) {
article.id = articles.length;
articles.push(article);
};
model.updateArticle = function (bookmark) {
var index = _.findIndex(articles, function (a) {
return a.id == article.id
});
articles[index] = article;
};
model.deleteArticle = function (article) {
_.remove(articles, function (a) {
return a.id == article.id;
});
};
}
angular.module('app.article.model', [])
.controller('ArticleController', ArticleController)
.service('Article', ArticleModel);
})()

how to load config file to an angular Object

I have a simple config page set up on my nodeJS server.
4 inputfields to store some IPs.
those fields are bound to
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
$scope.formData = {};
loadConfig();
$scope.$watchCollection('formData',function() {
saveConfig($scope);
});
});
Every change in the model calls the saveConfig(), which saves the config on the server:
function saveConfig($scope) {
socket.emit('save_config', {config: $scope.formData});
}
This seems to work. The Server correctly prints the content of the received object and there is no error in the saving process.
Now i want to LOAD the config into the angular Model, everytime the page is opened.
loadConfig() tells the server to load the config.json, parse it, and send it to the browser:
socket.on('load_config', function(data) {
console.log("[INFO] Config received:");
angular.element(document.getElementById('config')).scope().formData = data;
});
but it doesn't seem to work.. on page refresh, all the fields are empty.
besides, $scope.formData = {}; empties the object, so the config is immediately overwritten. how can i prevent this? (i don't know if this is actually the whole problem)
Is there anything terribly wrong with my approach?
Thanks
UPDATE:
It seems not to be completely wrong...
on refresh, the inputs are empty, but if i start typing and console.log the formData Object, it seems to have loaded the values in a weird, nested way
{"config":{"config":{"config":{"config":{},"ip2":"tzfrzftztrf","ip3":"ztu6tzzt6"},"ip2":"hhhkkizbi"},"ip2":"hhkkkkööö"},"ip3":"h"}
this was 4 refreshes. So it seems to work somehow, but not load it correctly
You can create service for loading configuration and inject it you module like
var formApp = angular.module('formApp', [])
formApp.service('LoadConfigService', function($http) {
return({
loadConfig: function() {
var promise = $http.get('config.json').then(function (response) {
return response.data;
});
return promise;
}});
});
.controller('formController', function($scope,LoadConfigService) {
$scope.formData = {};
LoadConfigService.loadConfig().then(function(data) {
//Action After response
});
$scope.$watchCollection('formData',function() {
saveConfig($scope);
});
});

Incomplete View Loading Before Firebase GetRecord is Resolved

I'm having a problem loading a record from firebase into my view when directly linking to the intended route with the key as a routeParam. As shown below in my routeProvider I've specified the param later called in the SpecController. The problem is, if I directly type the url in or click an offsite link the model bindings are all "undefined" indicating that the record is not loaded.
// Snippet from RouteProvider
.when('/spec/:urlKey', {
templateUrl: 'views/spec.html',
controller: 'SpecController',
controllerAs: 'spec'
})
// Snippet from SpecController
var cKey = $routeParams.urlKey;
this.check = this.checkList.$getRecord(cKey);
After a bit of research it seems I should call a resolve in the routeprovider and run that second bit of code. Though I'm not sure if that's the problem or if it has to do with the way angular loads itself and the routeparams as well as the order thereof.
Just as a side note it is fully functional when I load the application from a separate route/view and then click a link within the application which then uses $location to set the url and param as shown below.
// Snippet from ListController
this.viewCheck = function(check){
var ref = this.checkList.$keyAt(check);
$location.path('/spec/'+ref);
};
The "key" I'm referring to as well as all other additional functions I'm using and referring to can be found directly at the following section of the Firebase API Guide: https://www.firebase.com/docs/web/libraries/angular/guide.html#section-arrays
I can't really reproduce the issue in a fiddle because the only way it happens is if you directly place the link in the url of a browser. I've made a small video showing the problem. When the video opens you see the result of entering the url directly, then by simply clicking "Home" and then "Back" it then loads appropriately. http://screencast.com/t/4OKRTVnc
As mentioned in the comments, you should use the Angular route resolution process based on promises. Here is a working plunkr demonstration, but the highlights are:
Build a Data Service that Returns Angularfire's Promises
There are many, many ways to structure and access your Firebase data, but the important thing here is to use the promises returned by Angularfire. This keeps you from making duplicate sync objects for the same data, and allows you to play nice with Angular.
testApp.factory("ChatDataService", ["$firebase",
function ($firebase) {
var rootRef = new Firebase("https://docs-examples.firebaseio.com/");
var chatDataService = {};
chatDataService.getChatRooms = function () {
if (!chatDataService.chatRoomsPromise) {
var chatRoomRef = rootRef.child("web/data/rooms");
var chatRooms = $firebase(chatRoomRef).$asArray();
chatDataService.chatRoomsPromise = chatRooms.$loaded();
}
return chatDataService.chatRoomsPromise;
};
chatDataService.getRoom = function (roomId) {
return chatDataService.getChatRooms()
.then(function (chatRooms) {
return chatRooms.$getRecord(roomId);
});
};
chatDataService.getRoomMessages = function (roomId) {
if (!chatDataService.messages || !chatDataService.messages[roomId]) {
chatDataService.messages = chatDataService.messages || {};
var roomMessagesRef = rootRef.child("web/data/messages").child(roomId);
var roomMessages = $firebase(roomMessagesRef).$asArray();
chatDataService.messages[roomId] = roomMessages.$loaded();
}
return chatDataService.messages[roomId];
};
return chatDataService;
}
]);
Return Promises From Resolve Functions
You can write a small route resolution function that uses your data service to get the correct data. Make sure you return a promise.
when("/room/:roomId", {
controller: "RoomController",
resolve: {
room: ["$route", "ChatDataService", function ($route, chatDataService) {
var roomId = $route.current.params.roomId;
return chatDataService.getRoom(roomId);
}],
messages: ["$route", "ChatDataService", function ($route, chatDataService) {
var roomId = $route.current.params.roomId;
return chatDataService.getRoomMessages(roomId);
}]
},
templateUrl: "roomView.html"
})
Keep Your Controllers Dumb
You could have done all the Firebase lookup and promise resolving in each controller. In this case, I kept the controllers dumb by letting Angular routing wait on promise resolution.
testApp.controller("RoomController", ["$scope", "$firebase", "room", "messages",
function ($scope, $firebase, room, messages) {
$scope.room = room;
$scope.messages = messages;
}
]);

Variable caching in AngularJS (factory)

I have the following controller in my application, but there is some strange behaviour that I cannot explain. I've numbered two of the lines to help with the description, they don't both exist at the same time in the live code.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
var cachedMovieList = [];
//Controller for movie list
app.controller('MovieListController', ['$http', function($http){
var mlc = this; //needed for the $http request
this.movies = cachedMovieList;
this.loaded = false;
this.error = false;
if(this.movies.length == 0) {
console.log("Grabbing new movie list from DB");
$http.get('data/movies.json').success(function(data){
mlc.movies = data;
mlc.loaded = true;
cachedMovieList = data; //(1)
}).error(function(data){
mlc.error = true;
});
cachedMovieList = this.movies; //(2)
} else {
this.loaded = true;
}
}]);
With the code as above with line (1) present and line (2) not present, I am able to cache the result so that when I flick between pages I don't need to constantly re-get the data.
However if I remove line (1) and insert line (2), the variable "cachedMovieList" is never populated. I would expect it to be based on the fact that "mlc.movies" was assigned to... but I cannot understand why this is the case?
Any advice welcome.
Implement a factory that retrieves the data. Use angular.copy to preserve the array reference when the data returns from the $http call.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
app.factory('movies', function($http) {
var movies = {
data: [],
loaded: false,
error: false
};
$http.get('data/movies.json').success(function(data){
angular.copy(data, movies.data);
movies.loaded = true;
}).error(function(data){
movies.error = true;
});
return movies;
});
Inject the factory into your controller:
//Controller for movie list
app.controller('MovieListController', ['$scope','movies', function($scope, movies){
this.movies = movies;
}]);
Factories (like services) are singletons. They are initialized once, and cached for the entire lifetime of the SPA.
Use the controller in the view:
<div ng-controller="MovieListController as ctrl">
<div ng-show="!ctrl.movies.loaded"> Loading... </div>
<ul>
<li ng-repeat="movie in ctrl.movies.data">
{{ movie.name }}
</li>
</ul>
</div>
If I've understood this correct, you're entering the if condition only when this.movies.length == 0. In such a case, this.movies will be null, so cachedMovieList would get populated with a null value.
Because (2) probably gets executed first before the $http.get() request is finished. $http.get() is an AJAX request.
If you want to cache, you might want to use $cacheFactory instead :)
I believe you are mistaking the live updation of values that happens in view to live updation that would happen with variable assignments. Your line 2 will set cachedMovieList to [] initially. I believe that is quite obvious. But you think that since callback updates this.movies that change would cascade to cachedMovieList. That won't happen as you are re-assigning the mlc.movies variable that means it refer to new variable instead of modifying existing value.
If you really want to make you logic work, please update mlc.movies variables like following
mlc.length = 0 // Empty the array
mlc.push.apply(mlc, data);
Please check following answer for more information
How do I empty an array in JavaScript?

Categories