1

我编写了以下 HTML 和 AngularJS 代码,以在单击按钮时更新 HTML 页面(视图)上的树。

单击按钮时,更改会出现几分之一秒然后消失。我无法找到原因。你能告诉我如何克服这个问题吗?

下面是 HTML 和 JS 代码。这在片段编辑器中有效,但在浏览器中无效。

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

module.controller("TreeCtrl", function($scope) {
  $scope.categories = [];


  $scope.$apply($scope.addTreeToView = function() {

    $scope.categories = [{
      title: 'Computers1',
      categories: [{
        title: 'Laptops1',
        categories: [{
          title: 'Ultrabooks1'
        }, {
          title: 'Macbooks1'
        }]
      }, {
        title: 'Desktops1'
      }, {
        title: 'Tablets1',
        categories: [{
          title: 'Apple1'
        }, {
          title: 'Android1'
        }]
      }]
    }, {
      title: 'Printers1',
      categories: [{
        title: 'HP1'
      }, {
        title: 'IBM1'
      }]
    }];



  });
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Tree Example</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body>
  <div ng-app="myapp">
    <div class="col-sm-10 col-sm-offset-1" ng-controller="TreeCtrl">

      <form action="#" method="post" class="form-horizontal" id="commentForm" role="form">
        <div class="form-group" id="div_submitComment">
          <div class="col-sm-offset-2 col-sm-10">
            <button class="btn btn-success btn-circle text-uppercase" type="submit" ng-click="addTreeToView()"><span class="glyphicon glyphicon-send" id="qazwsx"></span> Create Tree</button>
          </div>
        </div>
      </form>

      <div class="page-header">
        <h3 class="reviews">Tree</h3>
      </div>

      <script type="text/ng-template" id="categoryTree">
        {{ category.title }}
        <ul ng-if="category.categories">
          <li ng-repeat="category in category.categories" ng-include="'categoryTree'">
          </li>
        </ul>
      </script>

      <ul>
        <li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
      </ul>


    </div>
  </div>
  <script src="self.js"></script>
</body>

4

3 回答 3

2

尝试从按钮中删除 type="submit"

于 2015-05-07T17:20:49.290 回答
1

我使用的是 Bootstrap 的 Form 元素类型。这有一个动作属性。我删除了 action 属性。代码删除后工作正常

       < form method = "post"
      class = "form-horizontal"
      id = "commentForm"
      role = "form" >
        < div class = "form-group"
      id = "div_submitComment" >
        < div class = "col-sm-offset-2 col-sm-10" >
        < button class = "btn btn-success btn-circle text-uppercase"
      type = "submit"
      ng - click = "addTreeToView()" > < span class = "glyphicon glyphicon-send"
      id = "qazwsx" > < /span> Create Tree</button >
        < /div>
        </div >
        < /form>

于 2015-05-08T01:27:17.850 回答
1

因为执行“提交”操作后,您的 html 将被重新加载。所以您必须将“type="submit" 替换为 type="button" 并禁用“自动提交”。

于 2015-05-08T02:57:30.953 回答