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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With