By "is it okay", I'm looking less for opinion and more for solid reason(s) why this should/shouldn't be done.
Example:
$scope.myVar = null;
$scope.myFn = function() {
if ($scope.myVar) return $scope.otherFn();
}
It seems that the scope is for exposing data to the view, but now we're checking it as well.
Lastly, whatever the ruling on this, does using the Controller As syntax change things here? While using the scope this way seems inappropriate, it somehow seems okay when referencing this.
Again, to avoid this being labeled a 'conversation' question that isn't appropriate for Stack, I'm specifically looking for grounded reasoning why this practice is a bad idea.
Of course it's perfectly valid. The scope is there to hold data and functions used by the view, and this data is controlled by the controller. How could the controller control anything without accessing the data?
Related
I'm editing an existing code that has a lot of angular js expressions which are being detected as unsafe by our automated testing system. I was able to see the article below that describes my case, but I was not able to get any specific way to solve it (I'm mostly seeing $watch and $apply). I guess what I need to know here is where do I make changes on the code?
Related links:
http://blog.angularjs.org/2016/09/angular-16-expression-sandbox-removal.html
https://docs.angularjs.org/guide/security#angularjs-templates-and-expressions
Sample snippets on my code:
Your code looks perfectly fine. I think what you're missing is the "passing user provided content" portion of that warning.
In the first example the only thing you are passing to $apply is a function that YOU have defined, same as the second example. In the last example you don't pass anything to $apply.
The reason they have these warnings is because $apply can be passed a string to evaluate an expression on $scope.
In the same way that
{{$scope.hello = 'Hello, World'}}
will set the hello property of $scope
$scope.$apply('hello = "Hello, World"')
Will do exactly the same. now imagine you pass user defined content to this
$scope.$apply(userPassedString)
Now you have given a user the ability to run arbitrary javascript expressions in your apply function.
To see exactly what I mean by this (and how this is exploitable), I have created a codepen demo for you here: https://codepen.io/codymikol/pen/bGbzbvp
(You'll have to scroll down in the HTML to see the script, I was lazy and din't link it as a separate JS file \_('__')_/
Also if you REALLY want to understand how the above snippet is able to function (and where I learned about getting the function constructor in such a way) you should watch this video by liveoverflow: https://www.youtube.com/watch?v=DkL3jaI1cj0
This was made back when the AngularJS team was trying to create a sandbox around scope expressions to prevent XSS. There are a bunch of videos detailing different exploits people used to get around the sandbox. Because of how complicated creating a sandbox is and how often it was being exploited they decided to remove it entirely and just warn developers about passing user content in such a way.
Traditionally I have managed my Angular code like this
//File 1
angular.module('name',[])
//File 2
function TestController(){
}
TestController.prototype.// inherited stuff
angular.module('name').controller('testController',TestController);
This worked great and allowed me to partition my files easily. Now I try to upgrade to 1.3 and get the infamous...
Error: [ng:areq] Argument 'TestController' is not a function, got undefined
Of course this is due to this change which claims a desire to clean up the way people write code. What about this pattern is more complex? Is there a way to maintain this pattern without changing the global settings?
There is actually a comment on the page you linked to that had a fairly solid explanation.
Global controllers refer to your controllers being defined as function
on the window object. This means that they are openly available to
conflict with any other bit of JavaScript that happens to define a
function with the same name. Admittedly, if you post-fix your
controllers with ...Controller then this could well not happen but
there is always the chance, especially if you were to use a number of
3rd party libraries. It is much safer to put these controller
functions inside the safety of a module. You then have more control
over when and where this module gets loaded. Unfortunately controller
names are global across an individual Angular app and so you still
have the potential for conflict but at least you can't clash with
completely different code in the JavaScript global namespace.
So the idea is that global controller functions could conflict with any other global function in any javascript you use. So to eliminate the chance of a conflict with your own code or a third-party script, not using global controllers makes your code safer and more consistent.
As mentioned in the comments by #Brett, you can use IIFE around your prototyping. Here is an update of your plunk that uses that. The main change just looks like this.
(function() {
TestController.prototype.name = 'World'
})();
What comes to my mind is 2 things:
1) in that way functions wont be kept in memory more than they should.
2) if you minify your code, minifyer will have to generate new names for all global objects, which is sfine when you have small project, but will be a problem when it's not.
Also it should prevent tests to modify unnecessary data.
I wonder what's the best practice for a simple page containing a couple of radio buttons and checkboxes and other stuff controlling the visibility of page sections.
I started with something like
<div ng-if="radio1==3 || !button2" ....>
and immediately started to hate it. This page advocates against using functions in the view and actually I'll need the expression later again, so I should probably use something like
<div ng-if="visible1" ....>
and update visible1 accordingly. I tried
watch("radio1", function() {
$scope.visible1 = $scope.radio1 == 3 && !button2;
})
but it didn't work, probably because of the variables being scalars. Am I right?
I replaced $scope.radio by $scope.my_wonderful_model_aggregate.radio and it worked, but it was a bit too much to type.
Adding ng-click="updateVisible1();" to all the buttons works, too, but then I could use jQuery instead. I guess it's the most efficient solution, but speed isn't important here. And it's prone to forgetting and feels non-declarative and pretty redundant.
In my case, writing a single function which updates all the "visible*" variables based on other scope variables is easy and feels good. The function is idempotent, so it's OK when it gets called multiple times, but how can I ensure that it gets called only when needed?
Is there a better solution? I'm looking for best practices.
Necessitating the injection of a service in a controller in order to have access to data and/or functions can be thought of as both a pro and a con.
What I'm trying to determine is what are the objective "pitfalls" of utilizing the $rootScope for often used bits of data and or functions?
(Note: I'm not trying to start a religious war here, but instead be able to make well informed decisions.)
It's like polluting of global namespace in plain JavaScript. You are polluting your application's global space. It's never good to do that (in any of the languages).
But there are some reasonable usages of rootScope...Angular says:
Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.
I'd like to know if using
angular.extend($scope,MyService);
Does it break oop encapsulation principle ?
Does it smell like MyService.call($scope) ?
Could you face variable and function conflicts ?
Is this a bad/good practice?
Typically from my experience services are injected into the controller and then will be called from that scope. I wouldn't say that using extend to copy over functions and properties is necessarily bad, but it might mitigate some of the purposes of IoC (inversion of control), which is what injection in angular is based on.
Does it break oop...?
My understanding is that what you would get from this call is additional functions and service calls directly on your scope. This doesn't break OOP in the sense that scope is an object and would have functions applied. Provided those functions + properties make sense on the scope it seems like a fine thing to do from that perspective.
Does it smell like MyService.call($scope)?
As I said in the first paragraph - I don't see why you wouldn't just call the service and either share data or pass in references to objects to the service. Another pattern that is common in angular is to use a promise to process returned data in your scope. That looks like:
MyService.callFunction(parameters).then(function (data) {
// process data here. Since this runs in $scope you can also use $scope normally.
// $scope.$apply() is in progress and will complete when the function returns
});
All the service does is provide the data to the scope then. Point is that I think there are better patterns than "extend".
Can you face conflicts?
In the call angular.extend(a, b); data, properties and functions are copied from b to a. If something already exists on a it will be overwritten with the data from b. So technically the short answer is "yes", you can face conflicts.
The bottom line
So at the end of the day this isn't a bad pattern but there are probably more common patterns I would try to use first.