You can define the object (in your example, we're talking about myObject
) ahead of time in your controller on the $scope
object, and simply use ng-model
to bind the fields to the properties on the object. You do not have to define the object ahead of time, though. ngModel
will create the object for you when binding, if it can.
<form name="frm" ng-submit="myControllerFunc(myObject)"> From date: <input type="date" ng-model="myObject.fromDate" /> <br />To date: <input type="date" ng-model="myObject.toDate" /> <br /> <button type="submit">Submit</button> <small>Check console log for value upon submit</small> </form>
For the function, define it on the $scope
object in your controller. In this example, passing in the object is superfluous as you can just reference it on $scope
rather than an argument, but you may have your reasons.
$scope.myControllerFunc = function(obj) { console.log(obj); // do whatever you want with obj };
Demo.
For the sake of completeness, here's the body of the controller if you define things ahead of time.
$scope.myObject = { fromDate: null, toDate: null }; $scope.myControllerFunc = function() { console.log($scope.myObject); // do whatever you want with obj };
The view would not be any different except you can remove the parameter from ng-submit
:
<form name="frm" ng-submit="myControllerFunc()">
Mix and match according to your needs.
Also, you do not have to use ng-submit
to call the function as shown in my examples (I didn't see your edit that included this detail). You can just call myControllerFunc
from your button ng-click
in the same way I've used it in ng-submit
.