在输入文本框中不会调用解析器函数进行更改

时间:2014-02-18 05:57:43

标签: javascript angularjs angularjs-directive angularjs-model

我是解析器和格式化程序的新手。我有一个指令,将对模型的更改进行验证。这样做的另一种方法是$ 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。任何人都可以告诉我我做错了什么,为什么在我输入文本框时没有调用解析器函数?

2 个答案:

答案 0 :(得分:1)

这是一个迟到的回复,但供参考: 我想你在哪里错过了#34;胶水&#34;当ui发生变化时会调用<div class="avatar-view" title="Change the avatar"> <button class="btn btn-primary btn-block avatar-save"> Change Avatar </button> <img src="/scripts/cropper/img/picture.jpg" alt="Avatar" > </div> <input name="avatar" value="../cropper/img/20150729105134.png" id="avatar-val" type="hidden"> 。这应该是这样的:

$parsers

如需完整参考,请参阅this(非常棒)帖子。

答案 1 :(得分: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");
            });
        }
    };
});

有关调用link函数的详细信息,请参阅here