AngularJS - 在一个 html 标签中切换变量

AngularJS - Toggle Variable in one html tag

您可以在下面看到我的代码示例 - 该应用 运行 正常,因此当我单击 'Toggle' 时,该应用会在两个变量之间切换。

<body>
<div ng-init="value = 'off'" ng-app='app' ng-controller="myctrl">
<h1 ng-click="value = { 'on': 'off', 'off':'on'}[value]; event.PreventDefault;">Toggle</h1>
  <h3 ng-show="value == 'on'" >{{var1}}</h1>
  <h3 ng-show="value == 'off'" >{{var2}}</h1>  
</div>

<script>
(function () {
'use strict';

angular.module('app', [])
.controller('myctrl', myctrl);

function myctrl($scope){
  $scope.var1 = "Its on";
  $scope.var2 = "Its off";
}
})();
</script>

以下问题:我如何实现这个,或者我只需要一个 "h3" 标签来在变量之间切换的最佳实践是什么?因为我的 html 标签中还有很多其他信息,而且我总是重复我只是为了切换两个变量...

您可以使用布尔值来简化代码

<div ng-app='app' ng-init='value = false;' ng-controller="myctrl">
   <h1 ng-click="value = !value; event.PreventDefault;">Toggle</h1>
   <h3 ng-show="value" >{{var1}}</h1>
   <h3 ng-show="!value" >{{var2}}</h1>  
</div>

<script>
(function () {
'use strict';

angular.module('app', [])
.controller('myctrl', myctrl);

function myctrl($scope){
  $scope.var1 = "Its on";
  $scope.var2 = "Its off";
}
})();
</script>

可以直接在大括号中添加条件

<h3>{{value == 'on' ? var1 : var2}}</h3>

演示:https://jsfiddle.net/rgvj1nca/

您可以使用单个变量并在控制器中切换它的值。这样实现非常干净,你不会引入很多变量

<body>
<div ng-app='app' ng-controller="myctrl">
  <h1 ng-click="toggleValue()">Toggle</h1>
    <h3>{{var1 ? 'Its on' : 'Its of' }}</h3>
  </h1>
</div>

<script>
  (function () {
    'use strict';

   angular.module('app', [])
    .controller('myctrl', myctrl);

   function myctrl($scope){

     $scope.toggleValue = function () {
       $scope.var1 = !$scope.var1;
     };

   }
  })();
</script>
</body>

查看此 JSBin 中的工作实现:https://jsbin.com/tihiru/1/edit?html,js,console,output