AngularJS ng-show Not Working with ng-click?



我不明白当我用ng-click单击我的按钮时我的ng-show不起作用...感谢您的帮助。

<div ng-show="showMe == 1">
     <h5>Ajouter</h5>
     <input type="texte">
</div>
<table>
    <thead>
        <tr>
            <th>Numéro :</th>
            <th>Type de Produit :</th>
        </tr>
    </thead>
    <tbody ng-repeat="product in shopCtrl.tableProduct">
        <tr>
            <td>{{product.id}}</td>
            <td>{{product.name}}</td>
            <td class="text-right">
                <div>
                    <button ng-click="showMe = 1">Ajouter</button>
                </div>
            </td>
    </tbody>
</table>

gtlambert的答案是正确的。但是,如果您有多个级别的ng-repeat或其他执行相同操作的指令,则会遇到麻烦。

为了不遇到任何问题,请使用这样的对象:

$scope.params = {showMe:0};// init in controller
<div ng-show="params.showMe == 1">
<button ng-click="params.showMe = 1">

无论您使用多少 ng 重复/指令,这都将始终有效。

当您使用ng-repeat时,这将创建一个新作用域。要从ng-repeat内部访问主控制器范围,您需要使用 $parent

因此,将您的ng-click更改为$parent.showMe = 1,这将解决问题:

<button ng-click="$parent.showMe = 1">Ajouter</button>

你去吧。我有一个工作的例子。 showMe将成为控制器的成员。

function ShopController() {
  this.showMe = false;
  this.tableProduct = [{
    id: 1,
    name: "Bar"
  }];
}
angular.module('app', [])
  .controller('ShopController', ShopController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ShopController as shopCtrl">
  <div ng-show="shopCtrl.showMe">
    <h5>Ajouter</h5>
    <input type="texte">
  </div>
  <table>
    <thead>
      <tr>
        <th>Numéro :</th>
        <th>Type de Produit :</th>
      </tr>
    </thead>
    <tbody ng-repeat="product in shopCtrl.tableProduct">
      <tr>
        <td>{{product.id}}</td>
        <td>{{product.name}}</td>
        <td class="text-right">
          <div>
            <button ng-click="shopCtrl.showMe = true">Ajouter</button>
          </div>
        </td>
    </tbody>
  </table>
</div>

最新更新