AngularJS 选择在选择值后清除

AngularJS Select cleared after Selecting value

本文关键字:选择 清除 AngularJS      更新时间:2023-09-26

我有一个通过JSON/REST填充的选择。它按预期填充下拉列表,并为我提供将值发布到数据库时所需的值(ID),但是一旦我选择一个选项,它就会清除选择中的所有标签,因此如果我错误单击或看到所选内容的标签,我将无法选择其他标签。

这是我的 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和选择选项 @ opt as opt.label for opt in categoryoptions指向相同的属性。因此,当您从选择中选择值时,它会使用所选值(对象)设置ngmodel categoryoptions,并且选项列表categoryoptions也相同,因此您会看到它被清除,因为categoryoptions不再是选择选项列表。对ng-model使用不同的属性名称,反之亦然。

例:-

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

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