如何在指令中访问ng-model值?

时间:2015-08-18 22:40:35

标签: angularjs google-maps angularjs-directive

我为谷歌地图自动完成创建了一个指令。一切都工作正常,但问题是当我需要访问输入的值并重新设置它。它不起作用。这是代码:

<div controller='mainCtr'>
    <span click='reset(destination)'>Reset</span>
    <div class='floatleft' style='width:30%;margin-right:40px;'> 
            <smart-Googlemaps locationgoogle='destination.From'></smart-Googlemaps>
            <label>From</label>
    </div>
</div>

在指令中:

angular.module('ecom').directive('smartGooglemaps', function() {
    return {
                    restrict:'E',
                    replace:false,
                    // transclude:true,
                    scope: {
                      locationgoogle: '='
                    },
                    templateUrl: 'components/directives/autocomplete/googlemap-search.html',
                    link: function($scope, elm, attrs){
                        var autocomplete = new google.maps.places.Autocomplete($(elm).find("#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(place);
                            $scope.locationgoogle = {};
                            $scope.locationgoogle.formatted_address = place.formatted_address;
                            $scope.locationgoogle.loglat = place.geometry.location;
                            $scope.locationgoogle.locationText = $scope.locationText;
                            $scope.$apply();
                        });
                    }
                }
})

这是html for directive:

<input id="google_places_ac" placeholder="Please enter a location" name="google_places_ac" type="text" class="input-block-level" ng-model='locationText'/>

该指令工作正常,我创建了一个隔离的范围(locationgoogle),将我需要的信息传递给父控制器(mainCtr),现在在mainCtr我有一个函数calld reset(),在我点击这个之后,我需要清理输入使其为空。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

从父控制器访问指令中的模型值的一种方法是将它放在隔离范围上并使用双向绑定标志=,就像使用{{{ 1}}属性。试试这个:

DEMO

<强> HTML

locationgoogle

<强> JS

<body ng-controller="MainCtrl">
    <button ng-click="reset()">Reset</button>
    <smart-googlemaps location-text="locationText"></smart-googlemaps>
</body>