Select不会自动更新使用ng-repeat呈现的ng-model更改

Select does not auto update on ng-model change rendered using ng-repeat

本文关键字:ng-repeat 更改 ng-model 更新 Select      更新时间:2023-09-26

我在指令中创建下拉菜单,如下所示:

<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>

尝试在$watch处理程序结束时调用$scope.$apply()

参见AngularJS文档中的Scope。