我有一个带有ng-change事件处理程序的下拉列表:
<label>Person:</label>
<select class="form-control" ng-model="select" ng-change="change()">
<option value="0">a </option>
<option value="1">b </option>
<option value="2">c </option>
</select>
在更改时,我将数组中的数据分配给$ scope.person:
$scope.change = function(){
$scope.person = $scope.persons[$scope.select];
};
数组:
$scope.persons = [
{'name': 'Peter'},
{'name': 'John'},
{'name': 'Mark'}
];
当选择某人时(例如$ scope.select == 0 / Peter),可以通过单选按钮向该人添加值($ scope.person.value):
<label><input type="radio" ng-model="person.value" value="1"> Value 1 </label><br/>
<label><input type="radio" ng-model="person.value" value="2"> Value 2</label><br/>
<label><input type="radio" ng-model="person.value" value="3"> Value 3</label><br/>
当一个值($ scope.person.value)被添加到一个人,并且我更改下拉列表时,我想删除/清除该值。因此,当您在下拉列表中重新选择该人时,$ scope.person.value是未定义的。
$scope.change = function(){
//This is not working
delete $scope.person;
// This is not working either
$scope.person.value = '';
$scope.person = $scope.persons[$scope.select];
};
我想知道在更改下拉列表时如何清除$ scope.person.value中存储的值。现在,当我重新选择人时,仍然定义变量。 Here is a working example.
答案 0 :(得分:0)
我认为该变量仍然保存,您应该自己删除该值:
$scope.change = function(){
delete $scope.person;
$scope.person = '';
$scope.person = $scope.persons[$scope.select];
//Remove the assigned value
delete $scope.person.value;
};
答案 1 :(得分:0)
你的问题就在这里,
$scope.person = $scope.persons[$scope.select];
当你这样做,然后分配一个'value'属性,你实际上修改了人物数组中的对象。试试下面,
$scope.change = function() {
$scope.person = angular.copy($scope.persons[$scope.select]);
console.log($scope.person);
};
$scope.$watch('person.value', function(n) {
console.log(n);
});
答案 2 :(得分:0)
正如@Kevin Sanchez所说,你需要从人那里删除value
。
喜欢这个delete $scope.person.value
;
jsfiddle上的实例。
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.persons = [{
'name': 'Peter'
}, {
'name': 'John'
}, {
'name': 'Mark'
}];
$scope.change = function() {
if ($scope.person)
delete $scope.person.value;
$scope.person = $scope.persons[$scope.select];
};
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<label>Person:</label>
<select class="form-control" ng-model="select" ng-change="change()">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
</select>
<br>
<br>{{ person }}
<br>
<br>
<label>
<input type="radio" ng-model="person.value" value="1">Option 1</label>
<br/>
<label>
<input type="radio" ng-model="person.value" value="2">Option 2</label>
<br/>
<label>
<input type="radio" ng-model="person.value" value="3">Option 3</label>
<br/>
</div>
</div>
&#13;