Angularjs "Controller as" or "$scope" - javascript

I would like to know what is the main difference between "Controller as" or "$scope" syntax in angularjs.
Do they have any performance impact,if yes which syntax is preferable.
"Controller as" syntax surely improve the readability of the code,as Knockout.js and other JavaScript framework follows the same syntax.
$scope will provide scope inheritance which sometimes give us weird behavior like
<div ng-controller="firstController">
ParentController: <input type="text" ng-model="parent"/>
<div ng-controller="secondController">
ChildController: <input type="text" ng-model="parent" />
</div>
</div>
app.controller('ParentController', function ($scope) {
$scope.parent = "parentScope";
}).controller('ChildController', function ($scope) { /*empty*/ });
a) Initially child will get the parent property and it displays 'parentScope' when we update parent child will also get updated. But if we have changed the child property now updating the parent doesn't modify child as it has got its own scope property.
b) If i am using controller as syntax changing child also updates the parent.

I've written a few answers to this question in the past, and they all essentially boil down to the same thing. In Angular, you are using $scope, even when you aren't expressly referencing it.
The ControllerAs syntax allows Angular to help you to write more efficient, fault tolerant controllers. Behind the scenes, when you use ng-controller="theController as ctrl", Angular creates theController as a property on $scope and assigns it as ctrl. You now have an object property you are referencing from scope, and are automatically protected from prototype inheritance issues.
From a performance perspective, since you are still using $scope, there should be little to no performance difference. However, since your controller is now not assigning variables directly to $scope on it's own, it does not need to have $scope injected. Also, the controller can much more easily be tested in isolation, since it is now just a plain JavaScript function.
From a forward thinking perspective, it's well known by now that Angular 2.0 will not have $scope, but instead will use features of ECMAScript 6. In any previews released by the Angular team showing migrations, they first begin by refactoring the controller to eliminate $scope. If your code is designed without the use of $scope based controllers, your first step in a migration is already complete.
From the designer's perspective, the ControllerAs syntax makes it much clearer where objects are being manipulated. Having customerCtrl.Address and storeCtrl.Address makes it much easier to identify that you have an address assigned by multiple different controllers for different purposes than if both used $scope.Address. Having two different HTML elements on a page which both are bound to {{Address}} and knowing which one is which only by the controller the element is contained in is a major pain to troubleshoot.
Ultimately, unless you are trying to spin up a 10 minute demo, you really should be using ControllerAs for any serious Angular work.

I would definitely recommend Controller As syntax.
It's cleaner, more efficient, you can organise your code much more and it's the new way of doing AngularJS.
Unless you're working with a team used to the $scope syntax, definitely use Controller As.

Related

When to use $scope in AngularJS Web application?

I recently started to work with AngularJS and got the hang of the basics for it, but in the examples I've seen around, I came to find two different approaches in them.
Making the variables and functions private:
function myController(){
var controller = this;
controller.myVar = 0;
controller.myFunction = function(){...};
}
And making them public through the $scope:
function myController(){
$scope.myVar = myVar;
$scope.myFunction = function(){...}
}
I can understand the need to make something private, but to expose variables and functions as public doesn't add up to me since it feel like the Single Responsability Principle is broken in those instances.
Is there a good reason to make something public like that? Are there alternatives to making something public? Or am I worrying too much?
$scope is the older way of doing things in Angular. The new way is to use the controllerAs syntax -- which is when you bind the value of this to a variable.
They both work, but the newer controllerAs way of doing things was introduced for a number of reasons -- chief of which being because it was closer to what they were expecting the Angular 2 way of being. Further, the controller as way of doing things, allows people to have nested code scope in a view and have a better understanding of where the interpolated values are coming from. For example:
<div ng-controller="controller1">
{{someVal}}
<div ng-controller="controller2">{{anotherVal}}</div>
</div>
Since scope is inherited in Angular, it is difficult to tell whether the value for anotherVal is coming from controller1 or controller2. When using the controllerAs syntax, it clears that up a bit by being able to do something like this:
<div ng-controller="controller1 as ctrl1">
{{ctrl1.someVal}}
<div ng-controller="controller2 as ctrl2">
{{ctrl2.anotherVal}}
</div>
</div>
Now, it becomes obvious where those values are coming from.
However, to answer your question directly, you may still need to use the $scope object when you hope to access certain angular lifecycle hooks such as $scope.$watch, $scope.apply, etc.
I believe the main reason to make things public like that is for the purposes of testing and to let Angular "know" about certain data changes so it can have any "listening" views react and update to such changes.
You use $scope only when you do data-bindings or when you want to pass data between controllers, otherwise you don't have to do that.

Difference between using Angular $scope dependency and no dependency

There is something that i don't understand with Angular.
I'm new to Angular, and i don't remember where but the tutorial that teached me used this syntax do apply properties to a controller's scope :
app.controller('someCtrl', function(){
this.variable = "hey!";
});
So, i was starting my web app, everything was fine, then i wanted to add some socket.io interactivity with my node.js server. So i was looking for some tutorials on how to make them work together i was confronted to this syntax :
app.controller('someCtrl', ['$scope', function($scope){
$scope.variable = "hey!";
}]);
I thought it was weird, so i looked into Angular's articles about dependency injection and scopes, i found that it was actually the way everyone is doing it... I also started to see that it allows you to interact with $rootScope and other stuff, which is i guess the way to make controllers interact with each other. But i still don't see the difference between the two. Is the first one one which is used to teach people the basics of angular in order to easily introduce them to the scope and dependency injection concepts ?
Thanks in advance for your answer.
Yes, that is confusing as hell and I wish the Angular guys would only use the second. The first one is easier to read and understand for any JS developer, however the docs used to state (AFAIK, that is gone from the docs now):
Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.
Since some versions, the second syntax (which injects $scope via dependency injection) is typically used, even if it is somewhat frightening to newbies, what with the array in the function variable list (which is needed for minification) and all.
The situation gets worse, though, because lately this makes a comeback in slightly different form, the "controller as" syntax:
HTML
<div ng-controller="MainController as main">
{{ main.someProp }}
</div>
Javascript
app.controller('MainController', function () {
var model = this;
model.someProp = 'Some value.'
});
So, most likely what you read is the "controller as" syntax that is currently pushing back more and more the second, dependency injection form. You can differentiate it from old examples if you look at the HTML to find XxxController as yyyy.
Typically, you don't work with this all the time in your controller's functions since the scoping of this in Javascript can easily introduce bugs. Therefore it is preferable to assign this to some local variable immediately and then work with that variable (model in my example) like you would with $scope.
TL;DR: work with the "controller as" syntax to be future-proof, but know until recently, the best practice was injecting $scope.
Basically, You should directly inject the $scope as a dependency to avoid minification problems.
When doing a minification, $scope will be translated into e and Angular will not know how to use e itself.
var app=angular.module("myApp",[]);app.controller("mainController",function(e){e.message="OH NO!"})
When directly injecting the dependency as you shown, $scope will not be renamed in any other way, so Angular will know how to handle it.
Take a look at this article on Scotch.io
I hope I've been helpful.

ng-init vs function in controller, which is better practice when using $parent?

I have a Bootstrap modal which corresponds to a ng-repeat list. I would like to access the ng-repeat scope data from its parent, which contains the modal. I do this so that when the modal button is clicked on the list, the corresponding data from the JSON appears in the modal.
I have found 2 ways of doing this, and I wonder which is the best alternative?
Method 1
View:
<li ng-init="myFunction(item,$parent)" ng-repeat="item in data.webapps_1.items>
Controller:
$scope.myFunction = function(item,parent){
parent.selected=item.counter-1;
};
Method 2 View:
<li ng-init="$parent.selected=item.counter-1" ng-repeat="item in data.webapps_1.items>
With nothing in the controller.
I have read in the Angular ngInit docs that
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.
But the list of special properties of ngRepeat does not include $parent.
So, which is the better practice? Including the expression $parent.selected=item.counter-1in the controller or in ngInit directive?
Thanks in advance
Either of the two fine really, so long as you're consistent. Depends on the scale of the app though.
IMO if the app is going to be large you'll want to go the function way, to better adhere to the whole MVC philosophy of decoupling and separation of concerns (http://victorblog.com/2013/03/18/angularjs-separation-of-concerns/).
ng-init="myFunction(item,$parent)"
It's a better structure because you want to keep most of your business logic in the javascript controllers, not in the view.
Personally, I prefer the ng-init approach. Mainly for consistency of the timing of the call (i.e. more like an "onLoad" event). I understand the concerns regarding SoC and that makes sense as well. However, I have seen some specific scenarios (particularly pages with a lot of directives), when changing scope variables with the = binding in the (non ng-init) function, caused extra (premature) digest loops. Obviously it depends on what you're actually doing in the function as well as your scope bindings, but in my opinion its best to just avoid the situation and use the ng-init directive across the board. Your experience may obviously vary wildly. Like others said just pick an approach and stick with it and be aware of the impact of every call that you're making in the function itself. :)
EDIT: Regarding the accepted answer, the example was used passing values to the init function in ng-init. And hes correct that is a violation of the pattern. I typically use parameterless init functions and call it like:
ng-init="model.init()"
Any reference to $scope or what have you would happen inside the function itself. I rarely pass anything to init, unless its a static value. For example in several cases on an ASP.NET WebApi project, I wanted minimize round trips to the server so I would resolve a value from the MVC View Model, which is just rendered and passed as a string like so:
ng-init="model.init(#model.myValue)"
In those cases its usually best to keep it to simple value types (i.e. string, int, etc), but I have occasionally for small directives such as one that does nothing but display a dropdown, I have passed arrays to pre-populate the dropdown binding. Those cases are extremely situational and this one in particular would obviously only work when using server side rendering of the template.

AngularJS: Passing data from a transclude directive to the isolated scope of a sub-directive

Based on this Plunker: http://plnkr.co/edit/GufJjrn3OxYVSf2oLD5n?p=preview
I have two directives, for the sake of simplicity, let's name them directiveBlue and directiveRed.
directiveRed has to be a sub element of directiveBlue.
The MainCtrl of our mini app has a simple array under the variable $scope.elements.
This variable is passed to the isolate scope that directiveBlue creates via the data-elements attribute. Notice that the directiveBlue has to be a transclude directive.
Then my main problem is, how do I pass the array of elements to the directiveRed without having to get it doing it via $scope.$parent.elements which seems to me, is a bad practice and then it makes the code tightly coupled.
Any changes to the elements in the deepest directive should then be synched with the rest of the scopes.
Is there any good practice or valid solution for this?
Thanks!
EDIT:
To be more concrete on my use case:
I've created a plunker (http://plnkr.co/edit/i2Busz6E8ehlkG3uEllh?p=preview) with a more concrete situation, where I want to have directive for an action group, I've implemented an option as a simple directive and I want to place my logic in the directives controllers. The method selectAll is pretty simple, but I can imagine having more complex actions which would require the elements from the top scope.
there are plenty of solutions, but without knowing what your goal is, it is more or less guessing.
The following quote is from the angular docs for $compile and describes the use of controller
(...)The controller is instantiated before the pre-linking phase and it is shared with other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior. The controller is injectable(...)
a fork of your plnkr to show how to access MainCtrl's $scope.elements in directiveBlue and directiveRed

AngularJS GlobalCtrl vs $rootScope vs Service

I am confused on a couple of things with Globals in Angular. Below is my pseudo code.
1) With the way I have my GlobalCtrl placed, I am able to reference my $scope.modalOptions from all of my controllers. That being the case, I'm confused as to why I see people adding global properties to $rootScope instead of just adding them like I am doing here. Is that just in case they want to inject it into a service or something?
2) Should I be using a service instead of adding properties and methods to my GlobalCtrl? If so, why?
<div ng-app="app" ng-controller="GlobalCtrl">
<div ng-view></div>
</div>
function GlobalCtrl($scope, $location) {
$scope.modalOptions = {
backdropFade: true,
dialogFade: true
};
}
The 'Main Controller' approach is definitely preferable to using $rootScope.
Scope inheritance is there, so why not leverage it. In my opinion, that solution works well for most cases, i.e. unless you need to have a parallel controller somewhere (that wouldn't be a child of Main). In that case, the best way to go is to use a service and inject it where needed. Services (or rather factories, because that's what you'll probably be using -- read more about them here) are singletons and work well for sharing data across controllers.
Important to know about scopes
Scope inheritance is pretty much regular JavaScript inheritance at play. You should tend to use objects for your data, because they are passed by reference.
If you have a primitive like $scope.myString = 'is of a primitive data type'; in your parent controller and try to overwrite the value in a child controller, the result won't be what you'd expect -- it will create a new string on the child controller instead of writing to the parent.
Suggested reading here
Final thoughts
If you are using the nested controllers approach, do not forget to still inject $scope (and other dependencies) in the child controller. It might work without, but it's slower and hard to test, and last but not least -- the wrong way to do it.
Finally, if you have a lot of state variables to keep track of and/or a lot of usage points, it's definitely a good idea to extract them into a service.
Generally speaking global variables are considered bad practice, as they don't encourage encapsulation, make debugging difficult, and promote bloated code. Here's a good discussion of global variables: http://c2.com/cgi/wiki?GlobalVariablesAreBad.
A good rule of thumb is to add properties and methods to the most local scope possible and use services to share data between modules.

Categories

Resources