6

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

<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]);
      }
    }
  };
});

问题是指令中的“watch”在组件的可重用性方面看起来并不是很好。所以我想最好的事情是能够做这样的事情:

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

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

4

3 回答 3

4

你需要做这样的事情

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 并且当相关值将在指令之外更改时,您将收到通知。

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

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

最后,您还可以使用本教程,您将在其中找到实现指令的所有材料,通过两种方式从您的应用程序到指令和相反的通信。

于 2013-09-14T11:05:33.657 回答
2

指令中没有范围声明:

html

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

指示

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);
            });                 
        }
    };
});
于 2015-06-13T19:53:06.000 回答
1

实现这一目标的一种简单方法是执行类似的操作

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

并在您的指令中将手表更改为

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

你可以走了

于 2013-09-14T10:58:55.913 回答