简体   繁体   中英

AngularJS: passing ngModel from controller to directive

I have a controller with an attribute directive inside it, that directive needs the ngModel of it's controller parent.

See this Plunkr .

Problem

Although the form loads correctly, the log inside the directive displays this:

a.$…t.aa {$attr: Object, $$element: R[1], fieldValidator: "", boundModel: "person", ngModel: undefined}

Any idea why ngModel is undefined and why boundModel contains the string 'person'? I've been staring too long at this ...

try this

app.directive('fieldValidator', [function(){
  return {
    restrict: 'A',
    scope: {
      boundModel: '='
    },
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs) {
      console.log($scope.boundModel);
    }
  }
}]);

like other said, there was no ng-model where you use this directive. boundModel: '=' is short for boundModel: '=boundModel'

And if you want to access boundModel then just use $scope.boundModel ignore what show in $attr guess that not what you need.

{ boundModel: '=ngModel' } means that you pass boundModel property through ng-model attribute. But in a template you don't use ng-model attribute. You have bound-model instead.

scope: {
   boundModel: '=ngModel'
},

You incorrectly use the scope variables. When you say '=ngModel', you say that there is an attribute on the directive with the name 'ng-model', which you want to use inside your directive as scope.boundModel.

It seems that you want to use ng-model controller, why do you not just use ng-model on your directive instead of boundModel?

You could rename the bound-model in you html to ng-model, and remove the scope from the directive. If you want to use the ngModelController you will need to inject this in the directive link function like this:

return {
    restrict: 'A',
    required: '^ngModel',
    scope: {},
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs, ngModel) {
      console.log($attrs);
    }
  }

With the ngModelController you can then set validity etc. of the person you bind to the ng-model in the html as documented here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM