【问题标题】:Select does not auto update on ng-model change rendered using ng-repeatSelect 不会自动更新使用 ng-repeat 呈现的 ng-model 更改
【发布时间】:2014-07-02 18:19:47
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    尝试按以下方式使用 ng-selected

    <option ng-repeat="site in defaultSites" value="{{$index}}" ng-selected="{{$index == selectedSite}}">
            {{site.name}}
    </option>
    

    【讨论】:

      【解决方案2】:

      尝试在 $watch 处理程序的末尾调用 $scope.$apply()

      the AngularJS docs on Scope

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        • 1970-01-01
        相关资源
        最近更新 更多