这是代码HTML:
<div ng-controller="SelectCtrl">
<p>selected item is : {{selectedItem}}</p>
<p> age of selected item is : {{selectedItem.age}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
这是代码JavaScript:
var app = angular.module('myApp', []);
app.controller('SelectCtrl', function($scope) {
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
console.log($scope.selectedItem); //this is undefined :(
});
我想在控制器中显示所选的值,但显然它是未定义的。
正确的方法是什么?
答案 0 :(得分:2)
@JoshLeeDucks is correct。当您尝试记录其值时,未在范围上定义$scope.selectedItem
。当用户通过选择<select>
输入中的元素为属性赋值时,Angular会识别出selectedItem
未定义并创建它。
使用$watch
:
console.log($scope.selectedItem); // undefined
$scope.selectedItem = 'someDefaultValue';
console.log($scope.selectedItem); // 'someDefaultValue'
$scope.$watch('selectedItem', function(newValue) {
console.log(newValue); // whatever `item.name` the user has selected
});