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

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

问题描述

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

I'm trying to write a directive to create a map component so 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 '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>

但我不知道在自定义指令中使用 angular 指令是否是一件好事,或者如何获取自定义指令链接函数中 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.

推荐答案

你需要做类似的事情

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.

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

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天全站免登陆