简体   繁体   中英

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
}

You can solve it in the other way plunker

In brief:

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

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>

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