2

我有以下指令:

  leafletDirective = angular.module("leaflet-directive", [])
  leafletDirective.directive "leaflet", ($http, $log)  ->
    restrict: "E"
    replace: true
    transclude: true
    template: "<div id=\"map\"></div>"
    scope:
      origin: "=origin"
      points: "=points"
      shape: "=shape"
      clearmarkers: "=clearmarkers"
      markers: "=markers"
    link: (scope, element, attrs, ctrl) ->

      scope.origin = [40.094882122321145, -3.8232421874999996]
      scope.points = []
      scope.shape = []
      #create a CloudMade tile layer and add it to the map
      @map = L.map(attrs.id,
                  center: scope.origin
                  zoom: 5
      )
      L.tileLayer("http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png",
                maxZoom: 18
      ).addTo @map


      #add markers dynamically
      updateMarkers = (pts) =>
        console.log "loading markers"
        scope.markers = []
        for p of pts
          lat = pts[p].lat
          lng = pts[p].lng
          latLng = new L.LatLng(lat,lng)
          marker = new L.marker(latLng).addTo(@map)
          scope.markers.push(marker)
        return scope.markers

      #/// Add Polygon
      updateShape = (points) ->
        console.log "loading shape"

      #///Watch for point changes///##
      scope.$watch attrs.points,( (value) ->
        updateMarkers value
      ), true


      #//Watch For Shape Changes///###
      scope.$watch attrs.shape,( (value) ->
        updateShape value
      ), true

我发现在页面上加载我的观察者

      #///Watch for point changes///##
      scope.$watch attrs.points,( (value) ->
        updateMarkers value
      ), true


      #//Watch For Shape Changes///###
      scope.$watch attrs.shape,( (value) ->
        updateShape value
      ), true

正在加载...我从它们加载的功能中看到这些消息。这是关闭的,因为两个 attrs 都没有改变。

这就是我加载 Angular 的方式:

app = angular.module("WhereToMeet", ["leaflet-directive"])

@MapCtrl = ($scope) ->

  $scope.clicked = ->
    $scope.points.push(
      {lat: 1, lng: 2}, {lat: 40.094882122321145, lng: -3.8232421874999996}
    )


  $scope.clear = ->
    $scope.clearmarkers($scope.markers)

  $scope.makeShape = ->
    $scope.shape = []
    $scope.shape = ["1"]

我不知道为什么它会在页面加载时加载。数据不变。除非 - 它只是被创建会这样做 - 我需要绕过。

4

2 回答 2

8

在观察者注册到作用域后,监听器 fn 被异步调用(通过 $evalAsync)来初始化观察者。在极少数情况下,这是不可取的,因为当 watchExpression 的结果没有改变时调用了侦听器。要在侦听器 fn 中检测这种情况,您可以比较 newVal 和 oldVal。如果这两个值相同(===),则由于初始化而调用了侦听器。--范围#$watch

于 2013-02-21T20:33:12.057 回答
5

我已将我的 $watch 语句简化为:

scope.$watch('someVar', function(newVal) {
  if (newVal) {
    // now, it's time to do something with scope.someVar
  }
});
于 2013-05-22T16:32:41.543 回答