在angular指令中获取模型值

时间:2015-02-09 16:08:00

标签: angularjs angularjs-directive bootstrap-datetimepicker

我为http://eonasdan.github.io/bootstrap-datetimepicker编写了一个角度指令,我可以对datetimepicker更新我的模型进行操作,但是当我尝试设置时,我遇到了问题在实例化期间,datetimepicker控件上的defaultDate与我的模型中的值相同。

这里是一名掠夺者:http://plnkr.co/edit/XUQSx7s0Fle2Xes77VrM?p=preview

的script.js

var app = angular.module('app', []);

app.controller('DemoCtrl', function($scope) {
    $scope.modelDate = new Date("01/01/2010");
});

app.directive('datetimepicker', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      // scope.$apply(); //This fixes the issue, but throws error in console
      element.datetimepicker( {
        defaultDate: ngModelCtrl.$modelValue
      })
      .on('dp.change', function(e) {
        ngModelCtrl.$setViewValue(e.date);
        scope.$apply();
      });
    }
  };
});

index.html的相关部分

<div class="container">
  <div class="form-group col-xs-6">
    <div class="input-group date" datetimepicker ng-model="modelDate">
      <input type="text" class="form-control" />
      <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
      </span>
    </div>
    Date from model: {{modelDate}}
  </div>
</div>

看起来问题是在datetimepicker实例化时,模型为null。在实例化datetimepicker之前执行scope.$apply()解决了这个问题,但在控制台中抛出了一个错误,这并不是一种正确的方法。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

强行对我们的范围进行$ apply呼叫并不是最明智的做法。 也许您应该尝试将其推迟到下一个摘要周期?

使用实用程序库(如Underscorejs),尝试以下操作:

_.defer(function(){scope.$apply();});