如何在Angular中发送未定义的对象关键帧而不进行硬编码

How send undefined object keys in Angular without hardcoding them

本文关键字:关键帧 编码 对象 Angular 未定义      更新时间:2023-09-26

我在一个对象中有一个键的列表,当我发送它们时,我试图检查其中哪些是未定义的。问题是,如果我发送一个未定义的密钥,它将被删除。现在,我正在将它们硬编码到scope变量中。

HTML:

<form ng-submit="createRecipe(recipe.alias, recipe.selectedCategory, recipe.description, recipe.instructions)">
            <label>Beer Name</label></br>
            <input ng-model="recipe.alias"></br>
            <label>Category</label></br>
            <select ng-options="beer.alias as beer.alias for beer in beerTypes" ng-model="recipe.selectedCategory" ng-change="filterByCategory(selectedCategory)">
            </select></br>
            <label>Description</label></br>
            <textarea ng-model="recipe.description" cols="50" rows="5" class="input-box"></textarea></br>
            <label>Recipe</label></br>
            <textarea ng-model="recipe.instructions" cols="50" rows="5" class="input-box"></textarea></br>
            <input type="submit" class="button-color btn btn-default"></br>
        </form>

角度函数:

$scope.createRecipe = function(alias, selectedCategory, description, instructions){
        $scope.recipe.alias = alias;
        $scope.recipe.selectedCategory = selectedCategory;
        $scope.recipe.description = description;
        $scope.recipe.instructions = instructions;
//Then I send it to the server
}

这是有效的,但它很难看,而且它仍然没有出现在后端。

如果需要定义键,即使值未定义,也可以在控制器中定义范围变量,并将设置为""。然后后端可以检查是否为空,例如在php中使用if (empty([your var]))

为了简化,当您提交数据时,数据在您的作用域中,因此函数可以只发送$scope.recipe数据。

$scope.recipe = {alias: '', selectedCategory: '', description: '', instructions: ''};
$scope.createRecipe = function(){
    //send it to the server
    $http.post('url', $scope.recipe).then(successCallback, errorCallback);
};
<form ng-submit="createRecipe()">
    <label>Beer Name</label></br>
    <input ng-model="recipe.alias"></br>
    <label>Category</label></br>
    <select ng-options="beer.alias as beer.alias for beer in beerTypes" ng-model="recipe.selectedCategory" ng-change="filterByCategory(selectedCategory)">
    </select></br>
    <label>Description</label></br>
    <textarea ng-model="recipe.description" cols="50" rows="5" class="input-box"></textarea></br>
    <label>Recipe</label></br>
    <textarea ng-model="recipe.instructions" cols="50" rows="5" class="input-box"></textarea></br>
    <input type="submit" class="button-color btn btn-default"></br>
</form>