AngularJS:点击按钮后显示一个html块

时间:2016-04-17 00:36:56

标签: angularjs angularjs-scope angularjs-controller

我正在尝试编写一个控制器来处理“新建”按钮的按钮单击。目标是最初隐藏较低的代码块(起始<div ng-show="buttonClick">)。单击“新建”按钮时,我希望显示较低的代码块。

我遇到的问题是,当我加载页面时,下面的代码块是可见的。它永远不会被隐藏。

{% extends "base.html" %}


{% block content %}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-10 col-sm-offset-1">
        <h2>Ratings</h2>
        <table class="table table-bordered">
          <thead>
          <tr>
            <th>Beer Name</th>
            <th>Beer Rating</th>
            <th>Notes</th>
            <th>Brewer</th>
          </tr>
          </thead>
          <tbody>
          {% for rating in ratings %}
            <tr>
              <td>{{ rating.beer_name }}</td>
              <td>{{ rating.score }}</td>
              <td>{{ rating.notes }}</td>
              <td>{{ rating.brewer }}</td>
              <td><a href="{% url 'rating-edit' rating.id  %}" class="btn btn-primary" value="{{ rating.id }}" name="edit">Edit</a></td>
              <td><a class="btn btn-primary" href="{% url 'rating-delete' rating.id  %}" value="{{ rating.id }}" name="delete" >Delete</a></td>
            </tr>
          {% endfor %}
          </tbody>
        </table>
        <div ng-app="myApp" ng-controller="myCtrl">
        <a ng-model="buttonClick" ng-click="is_clicked()" class="btn btn-primary">New</a>
      </div>
    </div>
  </div>






<div ng-show="buttonClick" >
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-10 col-sm-offset-1">
        <h2>Enter a new rating</h2>
        <form role="form" method="post">
          {% csrf_token %}
          <p>Beer Name: {{ form.beer_name }}</p>
          <p>Score: {{ form.score }}</p>
          <p>Notes: {{ form.notes }}</p>
          <p>Brewer: {{ form.brewer }}</p>
          <p><button type="submit" class="btn btn-primary">Submit</button></p>
        </form>
      </div>
    </div>
  </div>
</div>
</div>

<script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope){
          $scope.buttonClick = false;
          $scope.is_clicked = function() {
            $scope.buttonClick=true;
            console.log($scope.buttonClick)
         }
        })
</script>
{% endblock %}

2 个答案:

答案 0 :(得分:1)

在这一行

app.controller('myCtrl', function($scope)) {

删除最后一个)

当你的代码有效时,你可能会有一个&#34;闪烁&#34;阻止效果。它将出现在页面的加载中,然后当Angular启动时它将消失。如果你有&#34;眨眼&#34;效果,你需要在块上添加ng-cloack

<div ng-show="buttonClick" ng-cloak>

答案 1 :(得分:0)

我可能会这样尝试(未经测试):

<div ng-app="myApp" ng-controller="myCtrl">
       <div><a ng-click"buttonClick = !buttonClick" class="btn btn-primary">New</a></div>
       <script>
       var app = angular.module('myApp', []);
       app.controller('myCtrl', function($scope)) {
         $scope.buttonClick = false;
       }
       </script>