简体   繁体   中英

Angular Expression in ng-model

I'm trying to create a custom select element with an Angular directive.

The template in this directive contains a select element with a ng-model attribute that I want to get from the custom element.

<custom-select inner-model="modelName">
    <select model="{{model}}"></select>
</custom-select>

My problem is Angular doesn't allow an Angular expression as a value for the ng-model attribute.

I also tried to set an attribute with

link: function(scope, element, attributes) {
    element[0].childNodes[0].setAttribute('data-ng-model', attributes.innerModel);
}

It does take the attribute with the right value but it is still not working.

Here's my plunker : Plunker

You need to define an isolated scope. This will essentially bind the outer scope property assigned to inner-model attribute to internal scope property innerModel , which you could then use in your template.

app.directive('customSelect', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
       innerModel: "="
    }
    template: '<select ng-model="innerModel" data-ng-transclude></select>',
  };
});

Then you could do:

<custom-select inner-model="someScopeProperty">
  <option value="1">One</option>
  <option value="2">Two</option>
  ...
</custom-select>

(Although, I'm still puzzled by what you are trying to achieve)

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