简体   繁体   中英

How to bind return value to model in angular

I have multiple date time inputs in an angular app.

I want to set the value to now on blur of an input. I have accomplished this in multiple locations using ng-blur and calling a function.

The issue is I have multiple inputs and it seems stupid to have multiple functions doing the exact same thing other than which property to update on a model. What is the better way to handle this.

One other catch is that if there is already data to not update. Again I have the logic, but just need to know how to pass the model to a function and set the return value to it.

Create a function in your controller to set a passed object to the current date/time:

$scope.setNow = function(dateObject) {
    if (!dateObject) dateObject = new Date();
}

Then in your view, whatever date is being displayed can be passed to the model through whatever event you want to use (ng-blur, ng-click, etc)

<div ng-click="setNow(thisDate)">
    {{thisDate | date : 'hh:mm:ss'}}
</div>

<div ng-click="setNow(thisOtherDate)">
    {{thisOtherDate | date : 'hh:mm:ss'}}
</div>

<input type="text" ng-model="Task.StartDate" ng-blur="setNow(Task.StartDate)" >
<input type="text" ng-model="Task.EndDate" ng-blur="setNow(Task.EndDate)" >

Sounds like you could use a directive.

<input ng-model="myDateField1" my-date-setter>

Then your directive:

app.directive('myDateSetter', function () {   
  return {
    restrict: 'A',
    require: '^ngModel',
    link: function (scope, elem, attrs, ctrl) {
        elem.on('blur', function () {
           if (!elem.val()) ctrl.$setViewValue(new Date());
        });            
    }
  }
});

Then you can apply the directive wherever needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM