What's the meaning of require: 'ngModel'?

前端 未结 3 820
挽巷
挽巷 2020-11-28 03:02

This is the HTML for my directive:


In my directive I hav

3条回答
  •  鱼传尺愫
    2020-11-28 03:54

    The require:'ngModel' and require:'^ngModel' allow you to inject the model attached to the element or its parent element on which the directive is bound to.

    Its basically an easiest way to pass ngModel into the link/compile function instead passing it using a scope option. Once you have access to ngModel, you can change its value using $setViewValue, make it dirty/clean using $formatters, apply watchers, etc.

    Below is a simple example to pass ngModel and change its value after 5 seconds.

    Demo: http://jsfiddle.net/t2GAS/2/

    myApp.directive('myDirective', function($timeout) {
      return {
        restrict: 'EA',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$render = function() {
                $timeout(function() {
                    ngModel.$setViewValue('StackOverflow');  
                }, 5000);                
            };
        }
      };
    });
    

提交回复
热议问题