Are you viewing the area inside the user directive correctly?

I am trying to write a directive to create a map component so that I can write something like:

<map></map> 

Now the directive looks like this:

 angular.module('myApp') .directive('map', function (GoogleMaps) { return { restrict: 'E', link: function(scope, element, attrs) { scope.$watch('selectedCenter', function() { renderMap(scope.selectedCenter.location.latitude, scope.selectedCenter.location.longitude, attrs.zoom?parseInt(attrs.zoom):17); }); function renderMap(latitude, longitude, zoom){ GoogleMaps.setCenter(latitude, longitude); GoogleMaps.setZoom(zoom); GoogleMaps.render(element[0]); } } }; }); 

The problem is that the "look" inside the directive does not look very good, thinking about the possibility of reusing the component. So I think the best thing is to do something like:

 <map ng-model="selectedCenter.location"></map> 

But I don’t know if this is good using angular directives inside user directives or how I can get the object specified in the ng-model attribute in the link function with a custom directive.

+6
source share
3 answers

You will need to do something like this

 angular.module('myApp') .directive('map', function (GoogleMaps) { return { restrict: 'E', scope: { ngModel: '=' // set up bi-directional binding between a local scope property and the parent scope property }, 

Now you can safely watch your scope.ngModel, and when ever the corresponding value is changed outside the directive, you will be notified.

Note that adding the scope property to our directive will create a new isolated area.

You can refer to the angular doc around the directive here and especially the section "Object of the directive definition" for more detailed information about the properties of the area,

Finally, you can also use this tutorial , where you will find all the materials for getting a two-way directive from an application directive and the opposite.

+4
source

Without specifying the scope in the directive:

HTML

 <map ng-model="selectedCenter"></map> 

directive

 app.directive('map', function() { return { restrict: 'E', require: 'ngModel', link: function(scope, el, attrs) { scope.$watch(attrs.ngModel, function(newValue) { console.log("Changed to " + newValue); }); } }; }); 
+2
source

One easy way to achieve this would be to do something like

 <map model="selectedCenter"></map> 

and inside your directive change the clock to

 scope.$watch(attrs.model, function() { 

and you are good to go

+1
source

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


All Articles