我正在指令中创建下拉菜单,如下所示:
<select ng-model="selectedSite">
<option value="new">Add New Site</option>
<option value="line" disabled>------------------------</option>
<option ng-repeat="site in defaultSites"
value="{{$index}}">
{{site.name}}
</option>
</select>
指令是:
app.directive('siteForm', function() {
return{
restrict: 'E',
replace: true,
scope: {
site: '=',
defaultSites: '=',
selectedSite: '=',
},
templateUrl: '/views/templates/site_form.html',
link: function($scope, element, attrs) {
$scope.$watch('selectedSite', function(newValue, oldValue) {
console.log('Site selected:', newValue);
if (newValue !== undefined && newValue !== null) {
if (newValue !== "new") {
var value = $scope.defaultSites[parseInt(newValue)];
$scope.site.name = value.name;
} else {
$scope.site.name = "";
}
}
});
}
};
});
但是,当我在 selectedSite 中提供初始索引时,它不起作用并且始终显示第一个选项。例如。如果我们将 selectedSite 提供为“1”,则应选择值为“1”的选项,但这不会发生。
当我从下拉列表中选择选项时,其他一切都工作正常,包括 $watch 和 selectedSite 都会被填充。
我正在使用 AngularJS v1.2.10。
最佳答案
尝试按以下方式使用 ng-selected
<option ng-repeat="site in defaultSites" value="{{$index}}" ng-selected="{{$index == selectedSite}}">
{{site.name}}
</option>
关于javascript - Select 不会自动更新使用 ng-repeat 呈现的 ng-model 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24528139/