Search code examples
javascriptangularjsangularjs-scopevar

Angular JS if checked return value


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?


Solution

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