0

I'm trying to return a value to my $scope depending on if the checkbox is checked in angular JS but cannot seem to do so. Is there a way to get it to work?

HTML:

 <div class=" specialClause col-md-10 " >
<label for="TAR">Tag Along Rights: <input type="checkbox" ng-model="TAR" ng-change="myFunc()" name="TAR" id="TAR"/></label>

JS:

$scope.dej= function(){
   if($scope.TAR) {
       console.log('TAR');
       var tar = 'Yes';
   }else{
       console.log('no TAR');
       var tar = 'no';
   }
   return tar;
};

but i cant access tar outside the function. Is there a way to the value of tar's value outside the function?

2 Answers 2

1

First, your change function is myFunc and in angular you use dej function.

Second, you can write your logic in one line like so

return $scope.TAR ? 'Yes' : 'No'

Also, not really sure what you are tying to do. But in the below snippet the value Yes or No is added to a scope variable which is accessible in HTML for example.

Please let me know in the comments if this not what you were looking for.

See below snippet:

angular.module('myApp', [])
  .controller("example", ["$scope", function($scope) {
    $scope.tar = 'No'
    $scope.myFunc = function() {
      $scope.tar = $scope.TAR ? 'Yes' : 'No'
    }
  }])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="example">
    <label for="TAR">Tag Along Rights: <input type="checkbox" ng-model="TAR" ng-change="myFunc()" name="TAR" id="TAR" /></label>
    Tar is : {{tar}}
  </div>
</div>

1

tar is only available in the scope it is declared in, and your if and else statements open up a new scope.

The solution would be to define tar in their joint parent scope:

$scope.dej= function(){
   let tar;
   if($scope.TAR) {
       console.log('TAR');
       tar = 'Yes';
   }else{
       console.log('no TAR');
       tar = 'no';
   }
   return tar;
};

or alternatively just directly return:

$scope.dej= function(){
   if($scope.TAR) {
       console.log('TAR');
       return "Yes";
   }

   return "no";
};

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.