Angular JS 如果选中 return 值

Angular JS if checked return value

我正在尝试 return 我的 $scope 的值取决于是否在 angular JS 中选中了复选框,但似乎无法这样做。有没有办法让它工作?

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

但我无法在函数外访问 tar。 tar的值在函数外有没有办法取值?

首先,您的更改函数是 myFunc,在 angular 中您使用 dej 函数。

其次,你可以像这样在一行中写下你的逻辑

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

另外,不太确定你要做什么。但是在下面的代码片段中,值 Yes 或 No 被添加到范围变量中,例如可以在 HTML 中访问。

如果这不是您想要的,请在评论中告诉我。

见下面的片段:

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>

tar 仅在其声明的范围内可用,您的 ifelse 语句打开一个新范围。

解决方案是在它们的联合父范围内定义 tar

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

或者直接 return:

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

   return "no";
};