Controllers vs filters in angularjs - javascript

Both of them look like simple functions with the controllers having a scope with them. What exactly is the difference between them?

Controllers and filters may look like simple function to you but they are not the same.
Controllers are used mainly to control Angular scope object which is used to control views whereas filters are used to filter out some elements(also in view) based on user's choice. There are a lot of built in filters already and you can always create a filter on your own. You should never use Controllers for filtering, use filters instead.
Their names themselves provide the difference b/w them.
Read Controller Documentaion and Filter documentation to know more.

Controllers facilitate the interaction between the view, model and user, as per MVC.
Filters, on the other hand, modify data that is passed to them and output the result. They can be viewed as a pipeline that data passes through on the way from the model to the view.
Neither are "simple functions" but should be rather viewed as objects that serve specific purposes.

Related

Angular Data that does not affect the view: use directive, object, or function?

I have a repeated set of API calls in an Angular controller.
The relevant data is of course the API URI, POST or GET, some header data, and JSON objects. The API call always returns a JSON object.
I started to use a Directive but that seems most relevant for data that is used with $scope (e. g. in the View). This data runs under the radar and might eventually generate data used in the view but most usually not and most usually not in a way that can be abstracted.
So: Does this mean I shouldn't use a directive? If I don't use a directive, would it be better to use a JS Object (seems more modular) or Function (seems more variable friendly) to handle this code?
Yes, I get that objects can contain functions, but functions can also contain callbacks so...looking for kind of a "best practices" here. In terms of modularity and flexibility.
You should create Angular service for that.
https://docs.angularjs.org/guide/services
Your service will contain a method, lets say "getResults" which will make an API call and return either data or a promise ($http). Then you can inject you service to your controller and use that method to get the data and assign it to $scope.
An Angular service is certainly preferred to a more general JavaScript one because it allows you to take greater advantage of Angular's scope and other such things. Between Angular's Factory, Service, and Providers, a Service is the most in line with what you're trying to do since a Factory is too basic and generally used to solve smaller problems while a Provider is used -- as it says in the Angular docs -- "only when you want to expose an API for application-wide configuration that must be made before the application starts." Which is not what you're trying to do.

Angular.js: templates and handling data between views

I'm trying to grasp the main principles related to the next issues:
Templates
Data Handling
$resource vs $http
As i see it i'd like to implement few views in my app which share few html templates and also share some data. for simplifying my issue i'll describe a scenario which is almost equivalent.
as u can see there are 2 views (though there will be more!) who use 3 html markups while one of them is shared in both views (GeneralInfo). Also, both views share data which will be normally created while using one of the view's controller.
What principle of angular should be used to make sure that while changing the route i could keep my data shared between the views.
Should i use app.value('myVal', ..) which is Global variable?
Should i pass it like a service to all of my controllers?
More technically, how should i implement same html in both views? could u example that?
How should a view with it's markup contain 2 templates and how and when it is rendered?
what's the difference between $resource and $http and when each shouold be used?
1) should use a Service to share data between controllers. technically, you could attach values on $rootScope and it would be visible across controllers, but that is considered bad form and can cause problems later (like using global variables -- can definitely have unintended side effects as the project grows if someone accidentally attaches a conflicting value).
2) not sure exactly what you're asking here. you can load a partial based on the given route/state (using ngRoute or ui-router). two different routes could use the same generalInfo.html partial, but with different data being pulled in their respective controllers. is that what you're asking?
3) $resource is an abstraction of $http -- if you're pulling data from a REST server, $resource may be a better fit, as it abstracts a little of the wiring necessary. however, if the server varies from traditional REST principles too much, or if it's not REST at all, you may just want to roll your own data access directly with $http. Of course, if it's REST and more complex, also consider restangular -- which is a more feature rich abstraction.

AngularJS: need a best practice for hierarchical data

I am new to Angular, watched a number of videos and read docs, but not sure for i have it all compiled in my mind. I've seen a bunch of small simple pieces of code but never saw something complex. Do you know of docs/tutorials/examples to help me implement the following?
I want to make a SPA forum web application. The forum consists of numerous topic groups, each of which has topics inside, and each topic has multiple comments.
So this is a hierarchy of nested entities like this: Forum -> Topic Group -> Topic -> Comment.
In my SPA I'll need to CRUD any of them or load from server either a single entity (say Comment) or a complex view (a topic with all comments) depending on what user/admin wants.
I can't find an example dealing with the complex hierarchies. Should their controllers and models be nested or separated? How should I separate their CRUD methods? Do I put them all into the top level of $scope? How do I separate parent/child entities of the same $scope that are used in different controllers? What is the better way to substitute View and Edit templates for data being edited by user? Etc...
Or better, is there a sample for the task like mine?
Thanks
I avoid nesting controllers (making controllers depends on scope of their parent controllers), and instead make custom services through which controllers communicate.
Routing of controllers was the biggest issue for me. I've initially started by using ngInclude and handling routing manually, because AngularJS doesn't allow multiple ngViews. Solution was Angular UI Router. They have a simple example that can give you an idea on how to structure your navigation.
Basic principle is:
Any view can have sub view (and it's controller therefore contains sub-controller)
Controllers in hierarchy don't communicate directly through their $scopes. Rather they should use services or events ($scope.$emit, $scope.$on)
Any level of depth can be routed to (e.g. http://myforum.com/#/help-category/how-do-i/msg1)
Take my view with a grain of salt because I'm fairly new to Angular.
Since you're interested in scope inheritance here's an example, but this is discouraged for communication between controllers.
When a controller has a parent controller, then it's scope has a parent scope:
Parent controller:
$scope.Breakfast = 'eggs';
alert($scope.Breakfast); // Shows eggs
Child controller:
alert($scope.Breakfast); // Shows eggs, inherited value
$scope.Breakfast = 'muesli';
alert($scope.Breakfast); // Shows muesli, new value
Parent controller:
alert($scope.Breakfast); // Shows eggs, value remained same
$scope.Breakfast = 'burek'; // Child doesn't see this change anymore
You can get better description and illustrations in Angulars developer guide.
One quick note: don't forget that angular is all about your custom directives, so ideally your html for topic template should look like this:
<div ng-controller="TopicCtrl">
<comment ng-repeat="comment in topic.comments"></comment>
</div>
Angular really allows to write code unbeliavably DRY, so don't be afraid of directives, they will help you with achitecturing your application structure very much.

Best practice for node - mongo - angular

I have an app I am designing using node/mongo/angular, what I am not getting is how is the best way to get my data from mongo into my pages? I can use node, and thru my routes send back data from mongo with my template(hogan in this case), and bind using mustachejs. That works fine for most things. I have one screen that has a decent amount of drop down lists, to bind them for an edit scenario now seems a challenge. I would like to get them bound to an angular model and go about it that way. Is it better to get the data thru the route in node, then use something like ng-init and get it into angular? Or would I be better off not getting the data thru the route in node, and then using angular to perform a "get" request and bind that way?
From the documentation of ng-init, more precisely from the red warning alert at the top of the page...:
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
So no, do not use ng-init. While that can be a good strategy for lazy migrations from regular applications to single page applications, it's a bad idea from an architectural point of view.
Most importantly, you lose two things:
An API. The benefit of SPAs is that you have an API and that you're constantly developing and maintaining it, even before it has external users
A clean separation of concerns. Views are strictly limited to presentation, can be cached by the client and all data is transferred through JSON API endpoints.
I would say that the best way to get data from Mongo into your page, is as mnemosyn said, using an API.
Basicly, you can have your API route, f.ex '/api/data' configured and then it can be used by a angular service, (which can use ngResource to make things easier). Any controller that wishes to access this data can use the angular service to get it, do some stuff with it, and then update it using the same angular service.

In what ways does Backbone.js not support composed views?

I'm referring to this article here
http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/
In my current application I have two views. The first is the overall view which renders a table. The second view renders an individual row and is used by the main view. My row view could be separated into a separate file and used in any other component. In what way is this not composable? Perhaps I'm misunderstanding the terminology used in the article.
The author of that article is specifically referring to composable view templates, like Handlebars, in combination with the backbone view object.
He is essentially wanting to take a view-first approach to composition, where a template would define which views are composed in to the final view. This composition would also determine which objects are used to run the view.
For example, in EmberJS, you can configure a view template to be associated with a specific controller. Doing this, you can compose views in the template itself and the correct controller will be used. This is not possible with Backbone, even when using Handlebars - at least, not without some heavy customization. Backbone takes a "presenter-first" approach (to use the old Model-View-Presenter language) or a View-object first approach, where the view object itself controls which template is rendered.

Categories