Why ngModel's $render is not called when the model changes in AngularJS?

后端 未结 2 1128
挽巷
挽巷 2021-02-12 17:31

DEMO

Why in the following example $render is not called when the button is clicked?



        
相关标签:
2条回答
  • 2021-02-12 17:49

    The input directive is running after your directive and thus it's $render function is replacing yours.

    Set your directive's priority to something greater than 0. For instance:

    .directive("phoneNumber", function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function(scope, element, attrs, ngModel) {
          ngModel.$render = function() {
            alert('rendering');
          };
        } 
      };
    });
    

    And your $render will take precedence and you'll see your alert is called.

    0 讨论(0)
  • 2021-02-12 18:09

    ngModel.$render is working, when calling $render in the $apply.

    app.directive('changecase', function ($timeout) {
        return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function (scope, element, attrs, ngModel) {
          
            //format text going to user (model to view)
            ngModel.$formatters.push(function(value) {
                return value.toUpperCase();
            });
    
            //format text from the user (view to model)
            ngModel.$parsers.push(function(value) {
                return value.toUpperCase();
            });
    
            element.on('blur keyup change', function() {
                scope.$apply(function(){
                  ngModel.$setViewValue(ngModel.$modelValue);
                  ngModel.$render();
                });
                });
            }
        }
    });

    0 讨论(0)
提交回复
热议问题