Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 258
vcuongvu Avatar asked Oct 31 '22 14:10

vcuongvu


1 Answers

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)

like image 57
New Dev Avatar answered Nov 11 '22 03:11

New Dev