【问题标题】:Angular JS if checked return valueAngular JS如果检查返回值
【发布时间】:2021-09-08 06:45:17
【问题描述】:

我正在尝试根据是否在 Angular JS 中选中复选框,但似乎无法将值返回到我的 $scope。有没有办法让它工作?

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的值?

【问题讨论】:

    标签: javascript angularjs angularjs-scope var


    【解决方案1】:

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

    其次,您可以像这样将逻辑写在一行中

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

    另外,不确定您要做什么。但是在下面的 sn-p 中,值 Yes 或 No 被添加到一个范围变量中,例如可以在 HTML 中访问。

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

    见下sn-p:

    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>

    【讨论】:

      【解决方案2】:

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

      或者直接返回:

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

      【讨论】:

        猜你喜欢
        • 2020-07-23
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多