AngularJS中的指令在加载时触发$ watch回调函数

时间:2013-02-21 15:51:07

标签: angularjs angularjs-directive

我有以下指令:

  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

正在加载...然后我从他们加载的函数中看到这些消息。这是因为两个都没有改变。

这是我加载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"]

我无法弄清楚为什么它会在页面加载时加载。数据不会改变。除非 - 它只是被创造就会做到 - 我需要绕过它。

2 个答案:

答案 0 :(得分:8)

  

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

答案 1 :(得分:5)

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

scope.$watch('someVar', function(newVal) {
  if (newVal) {
    // now, it's time to do something with scope.someVar
  }
});