coldmind
coldmind

Reputation: 5417

Pass ng-model attribute to custom directive

So, I have a form, where I need to use a custom directive. What i need: pass the user model to the directive.

<form>
    <input type="text" ng-model="user.login">
    <input type="password" ng-model="user.password">

    <span ng-custom-directive ng-model="user.testfield"></span>

</form>

Directive template looks like this:

<span><input type="checkbox" ng-model="[HERE I NEED user.testfield TO WORK WITH user]"> </span>

How I can pass the user model to directive template?

After form submit I need user.testfield to be avaliable in the $scope.user like:

console.log($scope.user)
{
    login: 'test',
    password: 'test',
    testfield: true|false
}

Upvotes: 7

Views: 9699

Answers (2)

Volodymyr Pavlenko
Volodymyr Pavlenko

Reputation: 671

You can solve it in the other way plunker

In brief:

scope: {
    bindedModel: "=ngModel"
},
template: '<input type="text" ng-model="bindedModel">'

Upvotes: 10

coldmind
coldmind

Reputation: 5417

Well, I found similar question and resolved my problem in this way:

angular.module("myApp")
  .directive "ngCustomDirective", () ->
      restrict: 'A',

      scope:
        field: '@',
        model: '='

      template: '<span><input type="checkbox" ng-model="model[field]"></span>'

And directive usage will be:

<span ng-custom-directive
       ng-bind-model="user"
       ng-bind-field="testfield">
</span>

Upvotes: 0

Related Questions