从输入调用函数和更新视图

时间:2017-05-23 23:45:56

标签: angularjs

我有以下代码。我还有一个名为calculateAge(birthdate)的函数,我用它来更新年龄。我无法弄清楚该怎么做的是当人完成更新生日输入并从而更新年龄时,从输入中调用此函数。任何帮助都会很棒。

谢谢,

<fieldset ng-model="mySeat.seat" class="col-xs-12 session-registrant" ng-repeat="seat in seats | filter:cartPerf.perf_no">

<div class="session-registrant-field field-date" ng-if="mySeat.seat.ask_birthdate == 'Y'">
                <label for="birthdate-{{$ + cartPerf.perf_no + "mySeat.seat.customer_no}}">
                    {{bdayLbl}}

                    <span class="error-msg" ng-show="registrantForm.$submitted || registrantForm['birthdate-' + cartPerf.perf_no + mySeat.seat.customer_no].$touched">
                        <span ng-show="registrantForm['birthdate-' + cartPerf.perf_no + mySeat.seat.customer_no].$error.required">(Required)</span>
                        <span ng-show="registrantForm['birthdate-' + cartPerf.perf_no + mySeat.seat.customer_no].$error.date">(Invalid birthdate)</span>
                    </span>
                </label>
                <div ng-bind="mySeat.seat.age"></div>
                <input 
                       type="date" 
                       name="birthdate-{{$ + cartPerf.perf_no + mySeat.seat.customer_no}}" 
                       id="" 
                       value="{{mySeat.seat.birthdate | formatDate: mySeat.seat.birthdate:'yyyy-MM-dd' || ''}}" 
                       ng-model="mySeat.seat.birthdate" 
                       ng-required="mySeat.seat.bdatereq == 'Y'">
            </div>

</fieldset>

2 个答案:

答案 0 :(得分:0)

您可以使用ng-change在输入更改时调用该函数。

<input 
    type="date" 
    name="birthdate-{{$ + cartPerf.perf_no + mySeat.seat.customer_no}}" 
    id="" 
    value="{{mySeat.seat.birthdate | formatDate: mySeat.seat.birthdate:'yyyy-MM-dd' || ''}}" 
    ng-model="mySeat.seat.birthdate" 
    ng-required="mySeat.seat.bdatereq == 'Y'"
    ng-change="calculateAge()">

答案 1 :(得分:0)

您可以使用<input>上的ngChange directive在输入值发生变化后执行操作:

// Pretend this is your controller
function mySeat() {
  var vm = this;
  vm.seat = {
    // Whatever your seat property looks like
  };
  vm.calculateAge = function() {
    // Calculate the seat's age based on the current value of `birthdate`
    vm.seat.age = vm._someAgeCalcFun(vm.seat.birthdate);
  };
}

然后,在您的HTML中,将ng-change添加到<input>

<input 
  type="date" 
  name="birthdate-{{$ + cartPerf.perf_no + mySeat.seat.customer_no}}" 
  id="" 
  value="{{mySeat.seat.birthdate | formatDate: mySeat.seat.birthdate:'yyyy-MM-dd' || ''}}" 
  ng-model="mySeat.seat.birthdate" 
  ng-required="mySeat.seat.bdatereq == 'Y'"
  ng-change="mySeat.calculateAge()">