我有一个下拉列表,其中的项目是从$ scope.role填充的。现在,我需要在下拉列表中添加或选择值后从$ scope.role中删除值。我做了splice(index,1),它实际上只删除了第一个元素。需要帮助。
$scope.role = ['Actor', 'Director/ Asst. director', 'Lyricist',
'Music director/ Asst. director', 'Singer', 'Standup Comedian', 'Model',
'Cinematographer', 'Photographer', 'Script Writer', 'Choreographer',
'Editor/ Promo editor', 'Costume designer', 'Art director', 'Stunt artist',
'Voice-over artist', 'Graphic Designer', 'Screenplay', 'Dialogue',
'Back ground music'];
HTML:
<div class="row newRow">
<div class="form-group fields col-sm-2 col-xs-4">
<label>ROLE *</label>
<select name="role" class="form-control1 drop2" required ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
<div class="form-group col-sm-2 col-xs-4">
<button ng-click="AddRole()">Click to Add Role</button>
</div>
</div>
JS:
$scope.multiRoles = [];
$scope.role == $scope.dummy;
$scope.rolesAdded = false;
$scope.AddRole = function(index) {
debugger;
if ($scope.model.role !== undefined) {
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index, 1);
console.log($scope.role);
}
};
答案 0 :(得分:2)
你可以用两种方式做到这一点1)正如@nikjohn所建议的那样,通过在ng-click = "AddRole($index)"
中发送$ index下拉列表然后拼接或者
2)您可以使用绑定到下拉菜单的ng-model
找到所选选项的索引。
$scope.AddRole = function(){
debugger;
if($scope.model.role !== undefined ){
$scope.multiRoles.push($scope.model.role);
var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
$scope.role.splice(index,1);
console.log($scope.role);
}
};
答案 1 :(得分:0)
在您的HTML中,将$index
传递给AddRole
。否则,该函数不知道$index
是什么,并且还包含ng-repeat中的按钮:
<select name="role"
class="form-control1 drop2" required
ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}"> {{item}}
<button ng-click = "AddRole($index)">Click to Add Role</button>
</option>
</select>
在您的控制器中,我的评论中突出显示了额外的=
:
$scope.multiRoles = [];
$scope.role == $scope.dummy; // Why a `==` here? This should be a `=`
$scope.rolesAdded = false;
$scope.AddRole = function(index){
debugger;
if($scope.model.role.length){ // Cleaner method to verify that the array is non-empty
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index,1);
console.log($scope.role);
}
};
我还建议您使用Angular的ng-options
选择实施,因为:
在ngRepeat和ngOptions
之间进行选择在许多情况下,可以在元素上使用ngRepeat而不是ngOptions来实现类似的结果。但是,ngOptions提供了一些好处:
<select>
模型的分配方式更加灵活