'删除选择'不管用。以下是两个函数addNewChoice
和removeChoice
。 addNewChoice
正在运行removeChoice
无效。我不知道如何解决它。我的代码如下:
<?php $obj = 1;?>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope)
{
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function()
{
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function(index)
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(index,1);
};
});
</script>
<%--here is my html --%>
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice()">Remove</div>
答案 0 :(得分:1)
如果您只想删除数组中的最后一项,只需使用Array.prototype.pop()
$scope.removeChoice = function(){
$scope.choices.pop();
};
答案 1 :(得分:1)
好像你应该使用lastItem来删除和删除索引参数
$scope.removeChoice = function()
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
};
答案 2 :(得分:0)
您没有在ng-click中的removeChoice函数中传递索引。您需要在此函数中传递item的索引 -
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice(index)">Remove</div>
你可以从ng-repeat循环获得索引。
如果你想删除最后一项,那么你不需要在函数中传递索引键。但是你需要改变你的功能如下 -
$scope.removeChoice = function(index)
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
};
答案 3 :(得分:0)
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope)
{
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function()
{
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function()
{
console.log($scope.choices);
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
console.log($scope.choices);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--here is my html -->
<body ng-app="shanidkvApp" ng-controller="MainCtrl">
<div class="btn btn-primary" ng-click="removeChoice()">Remove</div>
<div class="btn btn-primary" ng-click="addNewChoice()">Add</div>
<p></p>
</body>