如何访问许多指令的范围变量?

时间:2013-11-04 19:30:28

标签: javascript angularjs angularjs-directive

我有一个指令,代表具有更改位置属性的人。我想一起访问所有位置,并使用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));
    }


});

1 个答案:

答案 0 :(得分: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指令中的工作原理。