为选定的 ng-model 设置默认值并管理 ng-change

Set default value on selected ng-model and manage ng-change

我无法为我选择的项目设置默认值,因为我知道我应该从 json () 使用该选择的值来显示另一种形式。

在我的控制器中,我这样设置了选择:

.controller('attributeFacetCtrl', function ($scope, tabsService, $location, contentService, attribute) {

    $scope.attribute = attribute;

    $scope.types = [{
        val: 'terms'
    }, {
        val: 'continuous'
    }];

    $scope.selected =  $scope.attribute.facet.data.type;

    $scope.isTerms = false;

    $scope.validateFrom = function() {

        var chk = $scope.selected.val;

        if (chk === 'terms') {
            $scope.isTerms = true;
        } else {
            $scope.isTerms = false;
        }
    };
})

$scope.attribute.facet.data.type="terms"

的结果

在我看来我有这个

 <div class="form-group">
                        <label class="wk-field-label">
                            <i class="icon-asterisk wk-prefield wk-mandatory"></i>
                            Type
                        </span>
                        </label>
                        <select class="wk-field-input" ng-model="selected"
                                ng-options="typeValue as typeValue.val for typeValue in types"
                                ng-change="validateFrom()"
                                required></select>
                    </div>
                    <div ng-if="isTerms" ng-repeat="orders in attribute.facet.data.order">
                        <div>
                            <label class="wk-field-label">
                                <i class="icon-asterisk wk-prefield wk-mandatory"></i>
                                Order
                                </span>
                            </label>
                    </div>
 </div>

问题是您将 $scope.selected 设置为一个字符串 ("terms"),但是当您加载 ng-options 时,它加载的是具有 val 属性.

如果你不一定需要$scope.selected是一个对象,那么你可以把你的ng-options改成下面这样:

ng-options = "typeValue.val as typeValue.val for typeValue in types"

如果您要求 $scope.selected 是一个带有 val 属性 的对象,那么您需要适当地设置它的初始值,而不是将它设置为字符串以便设置默认选择。

由于您希望通过字符串设置元素,因此请将您的 select 元素更改为以下内容:

<select 
  class="wk-field-input" 
  ng-model="selected"
  ng-options="typeValue as typeValue.val for typeValue in types"
  ng-change="validateFrom()"
  required
>
</select>

您可以在此处阅读有关如何使用 as 的更多信息:https://docs.angularjs.org/api/ng/directive/ngOptions

希望对您有所帮助!