简体   繁体   中英

Passing value from directive back to ng-model

I'll try to explain this thoroughly, though it is a little late.

I'm creating a directive that will have numerous input fields based on a dropdown. I'm essentially creating a customized option that I would like to pass into the parent. I'm passing the ng-model value from the calling template into the directive. I want to take the values of the customized options and pass that back to the value of the ng-model in the directive.

I have a plunker setup with what I'm attempting to do:

http://plnkr.co/edit/fhSgkSaLIBxs8BhQbdWW?p=preview

If you look at this code you can see in the html file that there is an input on the page and then it calls the directive. The input takes a value from a object name.first . The directive then takes a value name.test . In the directive I have a template that has an addition input field. I'm trying to take the value from this inner input field and pass the value back to the name.test value. Now, I know that I can set the ng-model of the directive input as the ngModel value that is passed down, but this is just a simple example and in the real code I will have additional checkboxes and radio elements that I would like to gather as an object and pass back to the ng-model . If it worked, then clicking the button will log an object as such { first: 'Felipe', test: { new_value: 'My Inner Value' } } .

Your use of ng-model for your directive makes it a bit confusing, since your ng-model in the directive and the input tag are not the same.

If I understand your problem correctly, the following should solve it

app.directive('myDirective', function($compile) {
  return {
    restrict: 'E',
    scope: {
      newModel: '=ngModel'
    },
    template: '<div class="some">' +
      '<p ng-bind="newModel"></p><input ng-model="newModel.new_value"></div>',
    replace: true,
    require: '?ngModel'
  };
});

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