Donot希望数组在angularjs

时间:2018-03-27 08:08:06

标签: angularjs angularjs-directive

我创建了一个数组示例。有一个文本框接受数字,点击添加后,它会将数字添加到已定义的数组中。在显示器上我希望它显示数组。但是发生的事情是,只要我点击添加按钮,HTML页面上就会同时显示该号码。我猜它是因为ng-model,但我希望它只在我点击显示按钮时显示。请帮忙。

<html  ng-app="Swabhav.Array">
 <head>
<title>Array</title>
<script src="angular.js"></script>
  </head>
  <body>
    <div ng-controller="ArrayController">
    <input type="text" ng-model="arraynumber">
    <button type="button"  value="Add"  ng-
      click="addElementToArray(arraynumber)">Add</button>
    <button type="button"  value="Display" ng-
        click="displayElementsInArray()">Display</button>
    <li ng-repeat="element in elements track by $index ">
       <h4> {{element}} </h4> 

    </li>

    </div>

    <script>

         angular.module("Swabhav.Array",[])
                .controller("ArrayController",
       ["$scope","$log",function($scope,$log){

                      $scope.numbers=[];
                      $scope.number="";

                      $scope.addElementToArray=function(number){
                          $scope.numbers.push(number);
                          $log.log("inside add "+ $scope.numbers)
                      }
                       $scope.elements=[];
                      $scope.displayElementsInArray=function(){
                          $log.log("Inside Display")
                          $scope.elements.push($scope.numbers);
                      }
                }])
    </script>

   </body>
   </html>   

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码,也可以查看此示例方案中的plunker link

<强>控制器:

  $scope.numbers=[];
  $scope.elements=[];
  $scope.addElementToArray=function(number){
      $scope.numbers.push(number);
      $scope.arraynumber='';
  };
  $scope.displayElementsInArray=function(){
      angular.extend($scope.elements, $scope.numbers)
  };