2013-09-24 173 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'控制器中,並且它不起作用 –

相關問題