AngularJS Select 在 Selecting 值后清除

AngularJS Select cleared after Selecting value

我有一个 select 是通过 JSON/REST 填充的。它按预期填充下拉列表,并在我 post 我的数据库的值时为我提供所需的值(ID),但是一旦我 select 一个选项,它就会清除 select 所以如果我误点击或看到我 select 编辑的标签,我不能 select 一个不同的。

这是我的 HTML:

<div ng-controller="pfcArticlePostCtrl">
<form ng-submit="createTask()">
    <p>
        <select data-ng-model="categoryoptions"
                data-ng-options="opt as opt.label for opt in categoryoptions"></select> the value is {{categoryoptions.value}}
    </p>
     <p>
        <input type="text" ng-model="articletitle"
               placeholder="add new task here">
    </p> 
    <p>
        <textarea ng-model="articlesummary"
               placeholder="add summary"></textarea>
    </p>
    <input type="submit" value="create">
</form>

这是我的控制器:

// Add new article
pfcControllers.controller('pfcArticlePostCtrl', ['$scope', 'pfcArticles', 'pfcArticleCategories', function ($scope, pfcArticles, pfcArticleCategories) {

var articleentry = new pfcArticles;

$scope.categoryoptions = [];

var articleCategoryNames = pfcArticleCategories.query(function () {

     // Foreach category entry, push values into categoryoptions array
    angular.forEach(articleCategoryNames, function (categoryvalue, categorykey) {

        $scope.categoryoptions.push({
            label: categoryvalue.categoryname,
            value: categoryvalue.categoryid,
        });
    })
});


$scope.createTask = function () {

    articleentry.articletitle = $scope.articletitle;
    articleentry.articlecategoryid = $scope.categoryoptions.value;
    articleentry.articlesummary = $scope.articlesummary;
    articleentry.articlelink = $scope.articletitle.replace(/\s/g, "-").toLowerCase();

    articleentry.$save();
}
}]);

那是因为您的 ng-model 和 select 选项 @ opt as opt.label for opt in categoryoptions 指向相同的 属性。因此,当您 select 来自 select 的值时,它将 ngmodel categoryoptions 设置为 selected 值(对象)并且选项列表 categoryoptions 也是同样,所以你看到它被清除了,因为 categoryoptions 不再是 select 选项列表。为 ng-model 使用不同的 属性 名称,反之亦然。

示例:-

<select data-ng-model="selectedCategory"
            data-ng-options="opt as opt.label for opt in categoryoptions">   
</select>

或者将值设置为数组本身的 属性,categoryoptions.selected 或者强制执行点规则(如果你可能需要)在你的控制器中定义一个对象 $scope.category = {}; 并设置ng-模型为 $scope.category.selected