Search code examples
javascriptangularjsbindingmode

Generate angular model properties by view, when view fields are empty


I have controller like this:

function ($scope) {
    $scope.Package = {};

    $scope.CreatePackage = function () {
        console.log($scope.Package);
    };
}

and view like this:

<input type="text" ng-model="Package.Name" />

<input type="number" ng-model="Package.Price" min="0" step="0.5" />

<button ng-click="CreatePackage()">Create New Package</button>

So, when I click this button not typing package name and price, I want my model to be:

{ Name: null, Price: null }

or

{ Name: '', Price: '' }

by default.

How can I make it automatically? is there any angular option to do this?


Solution

  • You can define the Name and Price attributes in your $scope.Package object initially. Binding the empty string will result in {Name: "", Price: ""} being the $scope.Package object inside your CreatePackage function.

    $scope.Package = {
        Name:'',
        Price:''
    };
    

    Hope this helps