Using this instead of $ scope inside the controller

I am trying to follow the style guide for angular, and it says that we should use this insted scope ...

Styleguide

Can someone explain to me when I can use this ?

Here is my attempt ..... What am I doing wrong?

I am trying to switch the 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 the classic $scope I would do this inside my role:

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

But with this it should look something like this (but doesn't work):

 var vm = this; vm.formEdit = formEdit; function formEdit(data){ data.formEditShow = !data.formEditShow; } 

Can anyone help me figure this out?

+5
source share
2 answers

When you use this (context) in the controller instead of $scope , you should use controllerAs when defining the html on the page to access the controller variables. Whenever you want to use a variable with this restriction, you can use the alias your controller. Below you can see that vm is a controller alias.

 ng-controller="myController as vm" 

Then, when accessing the controller method of the variable inside the ng-controller div, you need to use your controller alias, for example 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> 
+5
source

Assuming your controller is named FormController .

First step

The first step is to declare the route (or ng-controller value if you are not using a router) as such:

 FormController as form // name it semantically instead of a generic name 

Due to the above configuration, angular will be an alias as form instances of FormController .

HTML template

Then adapt your html template according to the alias (form) you provided. I modified your html to save only the essential part of the question. We call the form.reply and form.close .

 <a href="#" ng-click="form.reply()">REPLY</a> <a href="#" ng-click="form.close()">CLOSE</a> 

Controller declaration

In accordance with what we wrote above, our controller should look like this:

 myApp.controller('FormController', function () { var vm = this; vm.reply = function () { // ... } vm.close = function () { // ... } } 

Pay attention to the line var vm = this; ? Theoretically, we could get rid of this line and save the reply and close functions in the this object. But depending on the context, this does not apply to the same object. In the callback function, this will not refer to the controller, but to the callback function. This is why we cache this , which refers to the controller. We usually call this vm link for the viewmodel, because the controller controls the view.

+1
source

Source: https://habr.com/ru/post/1232392/


All Articles