如何删除angularJs中的数组元素

时间:2015-11-17 12:19:22

标签: arrays angularjs

在视图中我定义了一个像 - &gt;这样的按钮。 <button class="btn btn-default" ng-click="reset(path)">Reset</button>

我希望此函数重置已在控制器内定义的数组。

控制器代码

&#13;
&#13;
app.controller('mainCtrl',function(NgMap,$scope){
	 var vm = this;
	    $scope.path = [];
	    vm.addMarkerAndPath = function(event) {
	      $scope.path.push([event.latLng.lat(), event.latLng.lng()]);
	      console.log($scope.path);
	    };
	    
	    $scope.reset = function(){
	 
	    	$scope.path.length=0;
            $scope.path =[]; // also tried this but didn't work
	    }
});
&#13;
&#13;
&#13;

Html代码

&#13;
&#13;
<div class="panel panel-default" ng-controller="srmmobileHoardingCtrl as vm">
	<div class="panel-heading">
		Save Path for hoarding Advertisement
	</div>
<ng-map zoom="7" center="41.879535, -87.624333" on-click="vm.addMarkerAndPath()">
    <shape name="polyline" id="foo"
      path="{{path}}"
      stroke-color="#FF0000"
      stroke-opacity="1.0"
      stroke-weight="3">
    </shape>
  </ng-map>
  <div class="panel-body">
  	<Button class="btn btn-default">Save</Button>
  	<button class="btn btn-default" ng-click="reset()">Reset</button>
  </div>
  
  </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

使用切片删除元素。

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruits = fruits.slice(1, 3);

当您使用 fruits = [] fruits = new Array()时,会丢失角度使用的内部引用。

答案 1 :(得分:0)

感谢您的回复!!

我不知道为什么有人拒绝投票我的问题。 :/

我犯了一个非常愚蠢的错误。在开始时我没有正确初始化我的路径数组。即我的路径数组包含对象,每个对象包含[lat,lng]。

$ scope.path = [[,]]; //我用这种方式初始化,现在一切都很顺利。

控制器代码

'use strict';

app.controller('mainCtrl',function($scope,NgMap){
    $scope.path = [[,]];
    
    $scope.addMarkerAndPath = function(event) {
      $scope.path.push([event.latLng.lat(), event.latLng.lng()]);
      console.log($scope.path);
    };
    
    $scope.reset = function(){
    	console.log("reset function has been called");
    	console.log($scope.path);
    	console.log($scope.path.length);
    	$scope.path.slice(0,$scope.path.length);
    	$scope.path = [[,]];;
    	console.log("path array ");
    	console.log($scope.path);
    }
});
<div class="panel panel-default" ng-controller="mainCtrl">
	<div class="panel-heading">
		Save Path for hoarding Advertisement
	</div>
<ng-map zoom="7" center="41.879535, -87.624333" on-click="addMarkerAndPath()">
    <shape name="polyline" id="foo"
      path="{{path}}"
      stroke-color="#FF0000"
      stroke-opacity="1.0"
      stroke-weight="3">
    </shape>
  </ng-map>
  <div class="panel-body">
  	<Button class="btn btn-default">Save</Button>
  	<button class="btn btn-default" ng-click="reset()">Reset</button>
  </div>
  
  </div>

P.S如果我使用

,它也可以正常工作
  

var vm = this;通过控制器