Angular 未找到 $scope 变量

Angular $scope variable not found

我正在使用 google-places 指令,一切正常,但我突然注意到我的变量 $scope.location 没有在控制器中定义。但是在视图中它是可用的吗?

怎么了?谢谢

yuppiApp.directive('googlePlaces', function(){
    return {
        restrict:'E',
        replace:true,
        scope: {location:'='},
        template: "<input id='google_places_ac' ng-model='google_map' name='map' type='text' required/>",
        link: function($scope, elm, attrs){
            var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], {});
            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                var place = autocomplete.getPlace();
                $scope.location = place.geometry.location.lat() + ',' + place.geometry.location.lng();
                console.log($scope.location); 
                $scope.$apply();
            });
        }
    }
});

来自视图的代码:

{{ location }}

<google-places location="location"></google-places>

来自控制器的代码:

$scope.addNew = function () {
    console.log("Location: " + $scope.location);
};

我在指令和控制器的两种情况下都调用了 console.log($scope),看起来 $scope 有两个版本。我不明白为什么。

Object { $id: "0U8", $$childTail: null, $$childHead: null, .......
Object { $id: "00M", this: Object, $$listeners: Object

您必须在模板中的另一个指令中使用此指令,并且该指令正在创建子作用域。然后你最终得到两个范围,googlePlaces 指令将它写入子范围,控制器无法直接访问。

像这样更改您的代码:

再次将位置添加到您的指令以成为一个独立的范围:

yuppiApp.directive('googlePlaces', function(){
    return {
        restrict:'E',
        scope: {
          location: '='
        }
        ...

来自视图的代码:

{{ data.location }}

<google-places location="data.location"></google-places>

来自控制器的代码:

$scope.data = {
 location: null
};

这样两个作用域将共享同一个对象变量。这是应用的 'dot' 规则(所有绑定都应该有一个 . 在里面)。

我建议您了解控制器的 controllerAs 语法和指令的隔离作用域。