只需点击一下

时间:2015-06-26 14:09:42

标签: javascript angularjs

我试图切换来自两个不同ng-click个事件的文字。事实是,只有text1或text2应该同时出现。这是我目前的代码:

HTML:

<html lang="de" ng-app="ngToggle">
   <div ng-controller="BlubCtrl">
     <img ng-click="blob=!blob">
     <img ng-click="blub=!blub">

     <div ng-hide="blob">text1</div>
     <div ng-hide="blub">text2</div>
   </div>
<html>

JS:

angular.module('ngToggle', [])
    .controller('BlubCtrl',['$scope', function($scope){
        $scope.blub = true;
        $scope.blob = true;
}]);

2 个答案:

答案 0 :(得分:0)

假设您希望选项没有显示或最多只显示一个div,那么您只需要在范围内的函数中处理该逻辑。这可能如下所示。

$scope.toggleBlub = function() {
    $scope.blub = !$scope.blub
    $scope.blob = true;
}
$scope.toggleBlob = function() {
    $scope.blob = !$scope.blob
    $scope.blub = true;
}

您可以将点击次数更新为以下内容。

<img ng-click="toggleBlob()">
<img ng-click="toggleBlub()">

&#13;
&#13;
angular.module('ngToggle', [])
  .controller('BlubCtrl', ['$scope',
    function($scope) {
      $scope.blub = true;
      $scope.blob = true;

      $scope.toggleBlub = function() {
        $scope.blub = !$scope.blub
        $scope.blob = true;
      }
      $scope.toggleBlob = function() {
        $scope.blob = !$scope.blob
        $scope.blub = true;
      }
    }
  ]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ngToggle" ng-controller="BlubCtrl">
  <button ng-click="toggleBlob()">Blob</button>
  <button ng-click="toggleBlub()">Blub</button>

  <div ng-hide="blob">text1</div>
  <div ng-hide="blub">text2</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为Matthew的解决方案很好,但我发现设置ng-show代替ng-hide

更相关
angular.module('ngToggle', [])
  .controller('BlubCtrl', ['$scope',
    function($scope) {
      $scope.blub = false;
      $scope.blob = false;

      $scope.toggleBlub = function() {
        $scope.blub = !$scope.blub
        $scope.blob = false;
      }
      $scope.toggleBlob = function() {
        $scope.blob = !$scope.blob
        $scope.blub = false;
      }
    }
  ]);


<div ng-app="ngToggle" ng-controller="BlubCtrl">
  <button ng-click="toggleBlob()">Blob</button>
  <button ng-click="toggleBlub()">Blub</button>

  <div ng-show="blob">text1</div>
  <div ng-show="blub">text2</div>
</div>