I am trying to follow style guide for angular and there wrote we should use this
insted scope
...
Could someone explain me when I am able to use this
?
Here is my try..... What I am doing wrong?
I am trying to toggle form.... here is my html code:
<a href="#" ng-click="formEdit(x)" ng-if="!x.formEditShow">REPLY</a>
<a href="#" ng-click="formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>
With classic $scope
I would do like this inside my conroller :
$scope.formEdit = function(data){
data.formEditShow = !data.formEditShow;
}
But with this
it should look something like this(but don't work):
var vm = this;
vm.formEdit = formEdit;
function formEdit(data){
data.formEditShow = !data.formEditShow;
}
Anyone can help me to understand this?
When you are using this
(context) in controller instead of $scope
, you must use controllerAs
while defining html on page to access controller variables. Whenever you wanted to use variable bounded to this
on view you could use alias
of your controller. Below you can see vm
is alias of controller.
ng-controller="myController as vm"
Then while accessing controller method an variable inside ng-controller
div you need to use alias of your controller like ng-click="vm.formEdit(x)"
HTML
<a href="#" ng-click="vm.formEdit(x)" ng-if="!x.formEditShow">REPLY</a>
<a href="#" ng-click="vm.formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>