AngularJS - how to change the value of ngModel in custom directive?

后端 未结 5 1088
再見小時候
再見小時候 2020-12-23 09:53

Lets take a look to my directive:

angular.module(\'main\').directive(\'datepicker\', [
function() {
    return {
        require: \'?ngModel\',
        link:         


        
5条回答
  •  余生分开走
    2020-12-23 10:18

    What you tried is actually working: see this Plunker

    You don't "see" it in the input because changing the model this way doesn't call controller.$render() to set the new controller.$viewValue.

    But why don't you simply change the $scope value (unless you don't know it, but it would be weird):

    angular.module('main').directive('datepicker', [function() {
        return {
            require: '?ngModel',
            link: function(scope, element, attributes, controller) {
              var model = attributes['ngModel'];
              scope[model] = 'bar';
            }
        };
    }]);
    

    And in your html:

    
    

    EDIT: (dynamic solution)

    angular.module('main').directive('datepicker', [function() {
        return {
            require: '?ngModel',
            link: function(scope, element, attributes, controller) {
              // get the value of the `ng-model` attribute
              var model = attributes['ngModel'];
    
              // update the scope if model is defined
              if (model) {
                scope[model] = 'bar';
              }
            }
        };
    }]);
    

提交回复
热议问题