可以看一下自定义指令中的范围吗? [英] Is it ok watch the scope inside a custom directive?

查看:74
本文介绍了可以看一下自定义指令中的范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一条指令来创建地图组件,因此我可以编写如下内容:

I'm trying to write a directive to create a map component so I can write something like:

<map></map>

现在,指令如下所示:

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 'watch' inside the directive doesn't looks very well thinking in the reusability of the component. So I guess the best thing is being able to do something like:

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

但是我不知道在自定义指令中使用角度指令是否是一件好事,或者如何在自定义指令的链接函数中获取ng-model属性中指示的对象.

But I don't know if it's even a good thing using angular directives inside custom directives or how can I get the object indicated in the ng-model attribute in the custom-directive's link function.

推荐答案

您将需要执行类似的操作

You will need to do something like that

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 
      },

到目前为止,您可以安全地监视scope.ngModel,并且只要在指令外更改了相关值,就会收到通知.

as of now you could safely watch your scope.ngModel and when ever the relevant value will be changed outside the directive you will be notified.

请注意,将scope属性添加到我们的指令中将创建一个新的隔离范围.

Please note that adding the scope property to our directive will create a new isolated scope.

您可以在指令此处中,尤其是在指令定义对象"部分中,参考有角度的文档",以获取有关scope属性的更多详细信息.

You can refer to the angular doc around directive here and especially the section "Directive Definition Object" for more details around the scope property.

最后,您还可以使用此教程通过双向通讯将您的应用与指令相反的两种方式实现指令的所有材料.

Finally you could also use this tutorial where you will find all the material to achieve a directive with two way communication form your app to the directive and opposite.

这篇关于可以看一下自定义指令中的范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆