如何将监视添加到现有的角度指令?

时间:2014-09-10 07:58:25

标签: javascript angularjs

我正在使用此plunker中提供的指令。

app.directive('datetimez', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          element.datetimepicker({
            dateFormat:'dd/MM/yyyy hh:mm:ss',
            language: 'pt-BR'
          }).on('changeDate', function(e) {
            ngModelCtrl.$setViewValue(e.date);
            scope.$apply();
          });
        }
    };
});

该指令的目的是使用日期时间选择器here。 API提供了两种设置日期的方法:setLocalDate和setDate。 使用控件时,模型会更新,但是从代码更改模型时,视图不会更新。 我是angular指令的新手,但我的理解是我需要在指令中添加一个监视功能,并且可能使用datepicker的api函数来设置日期但不知道如何。

非常感谢任何帮助。

谢谢, 奥马尔。

1 个答案:

答案 0 :(得分:0)

伙计,我已经做了必要的修改,你可以找到它here

您只需添加$watch功能,如下所示:

app.directive('datetimez', function() {
    return {
        restrict: 'A',
        scope:{dateVal: '=ngModel'},
        require : 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          element.datetimepicker({
            dateFormat:'dd/MM/yyyy hh:mm:ss',
            language: 'pt-BR'
          }).on('changeDate', function(e) {
            scope.dateVal = e.date;
            scope.$apply();
          });

          scope.$watch('dateVal',function(newVal){
            var picker = $(element).data('datetimepicker');
            picker.setDate(newVal)
          });
        }
    };
});
相关问题