2013-11-04 53 views
0

我有一個指令表示位置屬性發生變化的人。我想一起訪問所有的位置,並使用類似angular-leaflet-directive的東西在地圖上繪製它們。我怎樣才能在一個地方訪問這些變量?我想我真的很接近它的工作,但我不知道哪個範圍可以訪問所有的指令變量。這是我到目前爲止?如何訪問多個指令的範圍變量?

的Index.html

<!DOCTYPE html> 
<html ng-app="app"> 
<head> 
<meta charset=utf-8 /> 
<title></title> 

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    <script src="http://code.angularjs.org/1.2.0-rc.3/angular.min.js"></script> 
    <script src="http://code.angularjs.org/1.2.0-rc.3/angular-resource.min.js"></script> 
    <script src="http://code.angularjs.org/1.2.0-rc.3/angular-animate.min.js"></script> 
    <script src="app.js"></script> 

</head> 

<body ng-controller='MainCtrl'> 

    <a href='' class='btn' ng-click='addPerson()'>Add new person</a><Hr> 

    <div id='people'> 
    <person lat="0.0" lng="0.0"></person> 
    <person lat="0.0" lng="0.0"></person> 
    <person lat="0.0" lng="0.0"></person> 
    </div> 
    <hr> 

    <div class="map"> <!-- this will be a directive representing a map --> 
     How do I access the lat and lon of each directive here? So I can plot them all on a map (which is also a directive ...) 
    </div> 

</body> 

</html> 

App.js

var app = angular.module('app', []); 

app.directive('person', function ($compile, $timeout) { 

    function link ($scope, elem, attrs, ctrl) {  

     $scope.lat = attrs.lat; 
     $scope.lng = attrs.lng; 


     $timeout(function changePosition() { 

      console.log('Changing position ...'); 
      $scope.lat = Math.random() 
      $scope.lng = Math.random() 

      $timeout(changePosition, 2000); 
     }, 2000); 
    } 

    return { 
     restrict: 'E', 
     replace: true, 
     template: "<span>Current Lat={{lat | number:2}}, Lng={{lng | number:2}}<br><br></span>", 
     link : link, 
     scope: {}, 
    } 

}); 

app.controller('MainCtrl', function ($scope, $compile) { 

    $scope.addPerson = function() { 
      console.log('Adding new person'); 
      var lat = Math.random() 
      var lng = Math.random() 
      angular.element('#people').append($compile('<person lat="'+lat+'" lng="'+lng+'"></person>')($scope)); 
    } 


}); 
+0

不應該「人物」數組已經在MainCtrl的$範圍內並使用ng-repeat呈現它們?添加一個人只會是數組中的一個推動,而不是你應該明確擺脫的$ compile/append事物。 –

回答

1

你只需要定義指令範圍部分的變量,就像你在控制器使用,你可以訪問這些鏈接功能。

app.directive('person', function ($compile, $timeout) { 

function link ($scope, elem, attrs, ctrl) {  

    $timeout(function changePosition() { 

     console.log('Changing position ...'); 
     $scope.lat = Math.random() 
     $scope.lng = Math.random() 

     $timeout(changePosition, 2000); 
    }, 2000); 
} 

return { 
    restrict: 'E', 
    replace: true, 
    template: "<span>Current Lat={{lat | number:2}}, Lng={{lng | number:2}}<br><br></span>", 
    link : link, 
    scope: { 
     'lat': '=', 
     'long': '=' 
    }, 
} 

}) 

您可以很好地瞭解範圍變量如何在來自what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs的指令中工作。