How to implement an ng-change for a custom directive

后端 未结 5 1060
滥情空心
滥情空心 2020-12-02 20:13

I have a directive with a template like

5条回答
  •  悲&欢浪女
    2020-12-02 20:26

    Samuli Ulmanen and lucienBertin's answers nail it, although a bit of further reading in the AngularJS documentation provides further advise on how to handle this (see https://docs.angularjs.org/api/ng/type/ngModel.NgModelController).

    Specifically in the cases where you are passing objects to $setViewValue(myObj). AngularJS Documentatation states:

    When used with standard inputs, the view value will always be a string (which is in some cases parsed into another type, such as a Date object for input[date].) However, custom controls might also pass objects to this method. In this case, we should make a copy of the object before passing it to $setViewValue. This is because ngModel does not perform a deep watch of objects, it only looks for a change of identity. If you only change the property of the object then ngModel will not realize that the object has changed and will not invoke the $parsers and $validators pipelines. For this reason, you should not change properties of the copy once it has been passed to $setViewValue. Otherwise you may cause the model value on the scope to change incorrectly.

    For my specific case, my model is a moment date object, so I must clone the object first before then calling setViewValue. I am lucky here as moment provides a simple clone method: var b = moment(a);

    link : function(scope, elements, attrs, ctrl) {
        scope.updateModel = function (value) {
            if (ctrl.$viewValue == value) {
                var copyOfObject = moment(value);
                ctrl.$setViewValue(copyOfObject);
            }
            else
            {
                ctrl.$setViewValue(value);
            }
        };
    }
    

提交回复
热议问题