【问题标题】:AngularJs, ng-show button table cellAngularJs,ng-show 按钮表格单元格
【发布时间】:2018-08-13 14:37:31
【问题描述】:

我有一个表格,每行显示一个按钮。我有一个要求,我必须有条件地在这些行中显示具有不同状态的按钮。所以在我看来,我对每个按钮都使用了ng-show

<table> 
  <tr>
    <td>row1 col1</td>
    <td>
      <button ng-show="!func1(param1,param2)" >
      <button ng-show="func1(param1,param2)">
    </td>
  </tr>
  <tr>
    <td>row2 col2</td>
    <td>
      <button ng-show="!func1(param1,param2)" >
      <button ng-show="func1(param1,param2)">
    </td>
  </tr>
</table>

在我的 .js 文件中:

$scope.func1 = function(p1,p2) {
    if(p1 === 'A' && p2 === 'B') {
      return true;
    } else {
      return false;
    }
}

现在控制器中的另一个函数更改了ng-show 函数的返回值。我可以在开发者工具中看到该函数现在返回一个不同的值,但视图没有得到更新。

您能告诉我我在这里做错了什么还是有更好的方法来实现这一点?

【问题讨论】:

  • 建议将返回值分配给 Scope 变量并将该变量放在 ng-show 上,例如:ng-show="isButtonShow" on function $scope.func1 = function(p1, p2) { //如果条件 $scope.isButtonSow = true }
  • 每一行的参数值不同。所以它必须为每一行执行。如果我让它基于变量,我如何为每一行执行它?

标签: javascript html-table cell ng-show


【解决方案1】:

所以从你的问题我的理解是,你需要在表中每一行的级别设置一个变量,并从一个函数更新所有行。

我假设您正在使用 ng-repeat 创建行。您可以使用可靠的ng-if 创建一个新范围,这样,当单行发生变量更新时,变量更新将单独隔离到该行,而不会传播到其他行。执行此操作的代码是。

<tr ng-repeat="item in items" ng-if="true">
      <td>row{{$index+1}} col{{$index+1}}</td>
      <td>
      <button ng-show="showThis" ng-init="p1 === 'A' && p2 === 'B'" ng-click="showThis = false;">A</button>
      <button ng-show="!showThis" ng-init="p1 === 'A' && p2 === 'B'" ng-click="showThis = true;">B</button>
</td>

这种方法的优点是当你从控制器更新变量时,我们可以用一个变量赋值来更新所有的行。以下是执行变量更新的函数。

  $scope.showB = function(){
    $scope.showThis = false;
  }
  $scope.showA = function(){
    $scope.showThis = true;
  }

简单地说,来自父作用域(控制器)的更新将传播到所有子作用域(ng-if 创建的新作用域),但子作用域不会传播!

下面是一个简单的例子来证明这一点!

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
$scope.showThis = true;
	$scope.items = [1,2,3,4,5];
  $scope.p1 = 'A';
  $scope.p2 = 'B';
  $scope.showB = function(){
  	$scope.showThis = false;
  }
  $scope.showA = function(){
  	$scope.showThis = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <table>
    <tr ng-repeat="item in items" ng-if="true">
      <td>row{{$index+1}} col{{$index+1}}</td>
      <td>
      <button ng-show="showThis" ng-init="p1 === 'A' && p2 === 'B'" ng-click="showThis = false;">A</button>
      <button ng-show="!showThis" ng-init="p1 === 'A' && p2 === 'B'" ng-click="showThis = true;">B</button>
    </td>
  </tr>
</table>
<button ng-click="showA()">show A</button>
<button ng-click="showB()">show B</button>
</div>

【讨论】:

  • 感谢您的建议和详细解释
  • 是的。我还尝试了调用 $scope.apply() 的原始代码,这似乎正在刷新行级 ng-show
  • @RJD 好的,在使用$apply() 时检查控制台是否有digest 错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2017-03-25
  • 1970-01-01
  • 2012-06-30
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多