2013-09-24 67 views
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 
    }; 

在谷歌-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总是返回undefined。

回答

1

您必须将控制器与视图(如果使用ngRoute)或使用ng-controller的元素相关联。事情是这样的:

<body ng-controller="ctrl">...</body> 
2

您需要的范围注入到控制器

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

注入$范围在你的控制器这样的:

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必须作为参数传入控制器的函数中。

+0

我不知道为什么,因为如果你在回调函数中看到你的控制器,你有没有PARAMS它不为我工作... –

+0

。但是在你的控制器中你使用$ scope。而在AngularJS中,如果你想使用$ scope,你必须将它传递给控制器​​函数的参数。你到底懂不懂呢 ? –

+0

是的,当然,我已经将$ scope注入到'ctrl'控制器中,并且它不起作用 –

相关问题