我是angularjs / javascript的新手,因此面临以下问题。
我尝试在js中设置选择的ng-model,但是在html中未显示“ selectedValue”。
请帮助!
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="o.name for o in selectNameOptions">
</select>
<br/>
<br/>
<i>selectedAccount: {{selectedName}}</i>
<br/>
<br/>
<i>selectAccountOptions: {{selectNameOptions}}</i>
<br/>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var name1 = {
name: "Emil",
age: 25,
label: "Emil 25"
};
var name2 = {
name: "Tobias",
age: 20,
label: "Tobias 20"
};
var name3 = {
name: "Linus",
age: 15,
label: "Linus 15"
};
$scope.selectNameOptions = [name1, name2, name3];
// set emil as intial selection
$scope.selectedName = {
name: "Emil",
age: 25,
label: "Emil 25"
};
});
</script>
<p>"Emil" is not selected, eventhough i have indicated the object in js.</p>
</body>
</html>
最佳答案
问题是您要为$scope.selectedName
分配一个新对象。尽管它匹配内部的所有值,但它仍然不是同一对象。
Angular通过对象的引用来匹配它们。因此,快速解决问题的方法是将name1
分配给$scope.selectedName
。请参阅以下片段中的修复程序:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var name1 = {
name: "Emil",
age: 25,
label: "Emil 25"
};
var name2 = {
name: "Tobias",
age: 20,
label: "Tobias 20"
};
var name3 = {
name: "Linus",
age: 15,
label: "Linus 15"
};
$scope.selectNameOptions = [name1, name2, name3];
// set emil as intial selection
$scope.selectedName = name1;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="o.name for o in selectNameOptions">
</select>
<br/>
<br/>
<i>selectedAccount: {{selectedName}}</i>
<br/>
<br/>
<i>selectAccountOptions: {{selectNameOptions}}</i>
<br/>
</div>
一个更明智的解决方法是使用对象的唯一标识符(例如
name
)作为select
框的值。var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var name1 = {
name: "Emil",
age: 25,
label: "Emil 25"
};
var name2 = {
name: "Tobias",
age: 20,
label: "Tobias 20"
};
var name3 = {
name: "Linus",
age: 15,
label: "Linus 15"
};
$scope.selectNameOptions = [name1, name2, name3];
// set emil as intial selection
$scope.selectedName = 'Emil';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="o.name as o.label for o in selectNameOptions">
</select>
<br/>
<br/>
<i>selectedAccount: {{selectedName}}</i>
<br/>
<br/>
<i>selectAccountOptions: {{selectNameOptions}}</i>
<br/>
</div>
请参考this link以了解有关
ng-options
指令的更多信息。