如何在angularJS中观看日期对象

时间:2015-04-20 14:48:00

标签: javascript angularjs angularjs-directive angularjs-scope

是否可以在angularJS中观看日期? 我有一个包含日期的ng模型,我想观看它,所以当它改变月份,年份或日期时,我收到了通知。

scope.$watch('ngModel',function(newVal){
    console.log(newVal);
  },true);

我有一个控制器,我给一个指令一个日期对象。 现在我想看那个约会对象。

module.directive('Datepicker',function(){
return {
 restrict:'E',
 scope:{
   ngModel:"="
 },
 link: function(scope, element, attrs) {
    //..other code here
    scope.$watch('ngModel', function(newVal) {
        console.log(ngModel);
    }, true);
  }
 }
});

2 个答案:

答案 0 :(得分:2)

我相信你是指令然后你应该只使用attrs.ngModel而不是ngModel,它应该在指令的链接/编译函数内部

<强>代码

app.directive('myDirective', function() {
    return {
        'restrict': 'E',
        scope: { ngModel: '='},
        link: function(scope, element, attrs, ngModel) {
            //..other code here
            scope.$watch('$parent.'+ attrs.ngModel, function(newVal) {
                console.log(newVal);
            }, true);
        }
    };
});

答案 1 :(得分:-1)

你的ngModel应该是$ scope:

function myController($scope){
   $scope.today = new Date()
      $scope.$watch('today',function(newVal,oldVal){
         //code goes here
      },true)
}