FDavidov
FDavidov

Reputation: 3675

Angularjs does not recognize "this"

I have a modal whose contents is generated by an JavaScript method (the reason being that the contents strongly depends on data retrieved from the DB, including hierarchy and its structure).

Initially, I had checkboxes deployed (as part of the generated HTML) as follows:

<input type="checkbox" 
       id="Chkbox_1" 
       onClick="Handle_Select(this,1,'Topic_34343')">

and, within the javascript (in Handle_Select) I could verify if the checkbox was checked or not by testing this.checked as follows:

Handle_Select = function (p_this,p_Topic_ID, p_Topic_Name) {

   if(p_this.checked) {...}

}

Now, I replaced the onClick by ng-click (as stated, I'm using AngularJS) and suddenly this no longer holds the properties of the input element but what appears to be the contents of the controller. Of course, the same function now looks:

$scope.Handle_Select = function (p_this,p_Topic_ID, p_Topic_Name) {...}

Upvotes: 0

Views: 48

Answers (2)

chukkwagon
chukkwagon

Reputation: 634

Angular comes with some handy directives that abstract a lot of the typical javascript boilerplate code. In this case, consider using the ng-model and ng-checked directives. ngModel will bind your input element to a value defined on your scope, and ngChecked will check or uncheck the input depending on a property you define:

<input type="checkbox" 
   id="Chkbox_1" 
  ng-model="your_scope_data" ng-checked="your_scope_data.is_checked">

so define $scope.your_scope_data in your controller, and then angular will tie it together with your template so that the values stay in sync. your_scope_data.is_checked is an arbitrary property of the data you bound with ng-model to the input element. You can also evaluate a simple expression in ng-checked if you want to perform comparisons, etc. Hope this helps, and good luck!

Upvotes: 0

Dmitriy
Dmitriy

Reputation: 3765

It is better to use this syntax:

<input type="checkbox" 
   id="Chkbox_1" 
   ng-click="Handle_Select($event, 1, 'Topic_34343')">

Angular code will be:

$scope.Handle_Select = function ($event,p_Topic_ID, p_Topic_Name) {
     var target = $event.target;
     if (target.checked) {
         // some code
     }
}

Upvotes: 2

Related Questions