Isolation of scope, but maintaining ngModel binding

I have a directive that will use ng-model to set its value.

The question is that this directive has internal components that will also be useless for the scope, so I need to isolate its scope, but still maintain the ng-model binding to the outside world.

How can i achieve this?

This is the directive:

 angular.module('app', []).directive('myDirective', function() { return { restrict: 'E', require: 'ngModel', link: function(scope, element, attr, ngModel) { // do stuff using ngModel controller }, replace: true, template: '<div><input ng-model="userInput" /></div>' }; }); 
 <my-directive ng-model="prop"></my-directive> 

As you can see, the directive should set prop as its value, but it should not expose userInput in the parent scope defined in <input ng-model="userInput"/> .

How can I only make prop available in the parent area?

+4
source share
1 answer

Normally, ngModelController is intended to be used with directives that do not create a new scope. The only way I found it to work with the isolation area is to use the same name in the selection area:

 scope: { prop: '=ngModel' } // must use 'prop' here! 

See my answer SO for more details: fooobar.com/questions/12603 / ...

You can also create a directive to create a new scope: true using scope: true . If you do this, then prop should be a property of the object, not a primitive: for example, ng-model='someObj.prop' . See the first script of this fooobar.com/questions/600184 / for more details on this approach.

This will still allow you to create your own (new) properties in the new child region of the directive without affecting the parent region. Well, you need to know how prototype object inheritance works - objects defined in the parent area will be visible and mutable in the area of ​​child objects. The primitives defined in the parent scope will be visible, but if you try to change the value of the parent primitive, you will create a child property that hides / shadows the parent property with the same name. (Here, more information on prototype inheritance can be found here .)

+3
source

Source: https://habr.com/ru/post/1468765/


All Articles