2013-02-21 47 views
2

$手錶回調函數,我有以下指令:指令在AngularJS被燒成負載

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都沒有改變。

這是我的負荷角度:

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"] 

我無法弄清楚,爲什麼它加載的頁面加載。數據不會改變。除非 - 它只是被創建將會這樣做 - 我需要解決這個問題。

回答

8

在向作用域註冊觀察者後,偵聽者fn被異步調用(通過$ evalAsync)來初始化觀察者。在極少數情況下,這是不可取的,因爲當watchExpression的結果沒有改變時調用監聽器。要在偵聽器fn中檢測到這種情況,可以比較newVal和oldVal。如果這兩個值相同(===),則由於初始化而調用偵聽器。 - Scope#$watch

5

我簡化了我的手錶$語句:

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

我通常使用這一個了。但是,我發現如果用戶刪除所有內容(大概是刪除過濾),它可能會導致搜索/過濾框等問題。在這種情況下,由於'someVar'現在是一個空白字符串,並且「falsey」,所以不會發生任何操作。並不總是一個問題,但需要注意的地方。 – squid314 2014-03-03 15:58:43

+0

好點!謝謝。爲了過濾,我也看看oldVal。 – 2014-03-03 18:09:34