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

标签 javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

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

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

相关文章:

javascript - ng-inspector 会减慢并导致页面崩溃。在哪里看

javascript - Angular : How to handle two-part directive

javascript - 在 AngularJS 指令中实现继承

javascript - 表单提交时在 React JS 中显示成功或错误消息

javascript - 如何在 raphael paper.image 中嵌入 base64 图像格式

javascript - 简单的 AngularJs 自定义指令不起作用

javascript - Angularjs - 指令 Controller 加载速度比应用程序 Controller 快 - 值未定义

javascript - 将 JavaScript 数字转换为 Dart double

javascript - 弹出窗口中的表格不起作用

angularjs - 集成测试时在AngularJS中使用$injector(不使用ngMock)