Saturday, 31 January 2015

angularjs controller -- this vs $scope vc var

When you do coding with controller, you may use:

this.aa = "";

and

$scope.bb = "";

and

var cc = "";


The differences  between them are :

1. this.aa will attach "aa" to this controller.
2. $scope.bb will attach "bb" to this $scope.
3. $scope is a property of current controller.
4. angularjs makes html ng-xxx binding to $scope, and make your coding life easy, nothing special.
5. you should not struggling with "this.aa" or "$scope.aa" because you will use "$scope" only if you want to access a property or a function from html.

6. var cc="" is a local varable.  it is only accessable in current class (in this case, it is a controller).

e.g. you may define your http call back function as :

var callbackfn = function(xxx){}

or

$scope.callbackfn = function(xxx){}

or

this.callbackfn = function(xxx){}


No problem, they are all runnable without any error.

But this is function is not testable (spec/karma/unitTest), because this function is not accessable from out side.


However, please avoid to mix them, and use $scope more. Because sometime your may use jquery or other libs, it will jump out of angular thread. The impact is you are not able to access $scope, even your code is in a controller. Keep in mind ! Because when you facing this issue you will find no clue. The errors you get are meaningless. In case if you have this problem please check my blog to find the solution (I have one blog for that).

No comments:

Post a comment