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

时间:2015-11-14 21:00:57

标签: javascript angularjs

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

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
}

这有效,但它很难看,而且它仍然没有显示在后端。

1 个答案:

答案 0 :(得分:0)

如果您需要定义键,即使值未定义,您也可以在控制器中定义范围变量并将其设置为""。然后后端你可以检查是否为空,例如在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>