Search code examples
javascriptangularjsangular-ngmodel

Setting empty text instead of null to ng-model in AngularJS


I need to get about 14 different input values from user to create a product and the input should not receive in the controller as null instead it should go as empty string

To achieve this the following is that I did: Controller:

var NewProductCatalog = {
    CustomerGuid: '00000000-0000-0000-0000-000000000000', SalesPartNo: "", Description: "",
    Name: "", Inventory: 0, UnitPrice: 0, BrandNo: "", TypeNo: "", LobNo: "", BrandName: "",
    TypeName: "", LobName: "", ManufacturePartNo: "", InventoryPartNo: "", EANCode: "",
    ImageURL: "", ProductType: "", DateAdded: "", Active: false, Tax: 0
};
$scope.newProductCatalog = NewProductCatalog;

.cshtml:

 <label for="SalesPartNo">Sales Part No *</label>
 <input type="text" required name="SalesPartNo" ng-model="newProductCatalog.SalesPartNo" class="form-control" />
 ...
 <input type="submit" ng-click="createProductCatalog(newProductCatalog)" />

Create function(controller):

$scope.createProductCatalog = function (NewProductCatalog) {
        var JsonString = angular.toJson(NewProductCatalog);
        CustomProductsServices.ProductCatalog_create(JsonString, function (callback) {
            if (callback.success) {
                $window.alert(callback.message);
            } else {
                $window.alert(callback.message);
            }
        });
    };

This allowed me to send an empty string when there user doesn't input any value.

The issue: When I try to enter a value in a text box and then delete/empty the text box and submit. I am not able to see the SalesPartNo in the resulting JSON string

Please point out the error of if my approach is wrong suggest me a better approach


Solution

  • Please remove attribute required from <input name="SalesPartNo" /> as angularjs not binding to model unless value is valid.

    Please demo here http://jsbin.com/wuhipe/1/edit?html,console,output

    <input type="text"  name="SalesPartNo" ng-model="newProductCatalog.SalesPartNo" class="form-control" />