4

我是解析器和格式化程序的新手。我有一个指令,将对模型的变化进行验证。要做到这一点的一种方法是$ watch,但从我所了解的情况来看,这不是一种好方法,因为它允许更新模型。在输入文本框中不会调用解析器函数

所以我一直在寻找的解析器,并试图将此代码

app.directive('myDirective', function($compile) { 


return { 
    restrict: 'E', 
    require: 'ngModel', 
    scope: { 

    }, 

    link: function($scope, elem, attr, ctrl) { 
     console.debug($scope); 
     ctrl.$formatters.push(function(value) { 
     console.log("hello1"); 
     return value; 
     }); 
     ctrl.$parsers.unshift(function(value) { 

     debugger; 
     console.log("hello"); 
     return value; 
     }); 
    } 
    }; 
}); 

但解析器函数永远不会被调用。格式化程序被调用一次。 Please see the plunkr。任何人都可以告诉我我在做什么错,为什么在我输入文本框时解析器函数没有被调用?

+1

尝试ctrl。$ parsers.push,仍然不起作用 – Abhik

回答

1

这是一个迟到的回应,但仅供参考: 我想你错过了“胶水”,将发生ui更改时将调用$parsers。这应该是这样的:

app.directive('myDirective', function($compile) { 

return { 
    restrict: 'E', 
    require: 'ngModel', 
    scope: { 

    }, 

    link: function($scope, elem, attr, ctrl) { 
     console.debug($scope); 
     ctrl.$formatters.push(function(value) { 
     console.log("hello1"); 
     return value; 
     }); 
     ctrl.$parsers.unshift(function(value) { 
     return value; 
     }); 
     scope.$watch('directive model here', function() { 
     ctrl.$setViewValue(<build model from view here>); 
     }); 
    } 
    }; 
}); 

有关完整的参考请参阅this(真棒)帖子。

0

您的link函数未被调用,因为关联的DOM元素没有改变,只是模型是。这工作:

HTML:

This scope value <input ng-model="name" my-directive> 

JS:

app.directive('myDirective', function($compile) { 
    return { 
     require: 'ngModel', 
     link: function($scope, elem, attr, ctrl) { 
      ctrl.$parsers.unshift(function(value) { 
       console.log("hello"); 
      }); 
     } 
    }; 
}); 

here更多的时候link函数被调用的。