Vladimir Djukic Vladimir Djukic - 7 months ago 26
AngularJS Question

Using this instead of $scope inside controller

I am trying to follow style guide for angular and there wrote we should use



Could someone explain me when I am able to use

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
I would do like this inside my conroller :

$scope.formEdit = function(data){
data.formEditShow = !data.formEditShow;

But with
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)"


<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>