0

ディレクティブから $scope プロパティにアクセスできない理由がわかりません。ドキュメントには、ディレクティブは新しいスコープを作成しないと書かれていますが、なぜ $scope プロパティにアクセスできないのでしょうか?

app.js で

'use strict';

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

climbingApp.controller('ctrl', function($scope) {

    $scope.initLocation = {
        lat: -54.798112,
        lng: -68.303375
    };

google-map.js で

'use strict';

climbingApp.directive('gmap', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '<div id="map-canvas"></div>',
            link: function(scope, iElement, attrs) {
                console.log(scope.initLocation);
            },
        }

    })

index.html で

  <html ng-app="climbingApp">
     <body>
    <gmap></gmap>

    </body>
    </html>

<script src="//code.angularjs.org/1.2.0-rc.2/angular.min.js"></script>

<script src="app/app.js"></script>
<script src="app/dependencies/google-maps.js"></script>

console.log常に未定義を返します。

4

3 に答える 3

0

次のようにコントローラーに $scope を挿入します。

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


    climbingApp.controller('ctrl', function($scope) {

        $scope.initLocation = {
            lat: -54.798112,
            lng: -68.303375
        };

        $scope.markers = [
            {
                'title' : 'prueba',
                'position' : [-54.798112, -68.303375] 
            },
            {   
                'title': 'prueba', 
                'position': [-54.798212, -68.303375] 
            }
        ];
    });


    'use strict';

    climbingApp.directive('gmap', function() {
            return {
                restrict: 'E',
                replace: true,
                template: '<div id="map-canvas"></div>',
                link: function(scope, iElement, attrs) {
                    console.log(scope.initLocation);
                },
            }

        })

plunkr の作業はこちら: http://plnkr.co/edit/fiK5viToLOVGobnAKZtB?p=preview

ログが表示されます。

$scope または $location は、コントローラーの関数にパラメーターとして渡す必要があります。

于 2013-09-24T20:51:04.200 に答える