0

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 ...

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

{ 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.

Comments

0
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.

2 Comments

And how would I need to change the html?
You will need to change bound-model="person" to ng-model="person"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.