从指令到对象的角度赋值

时间:2015-09-17 13:44:43

标签: angularjs directive assign

我有这个自定义指令:

var geo = angular.module('Geo', ['Gealocation']);

function SearchForm($scope){
$scope.location = '';
$scope.doSearch = function(){
    if($scope.location === ''){
        alert('Directive did not update the location property in parent    controller.');
    } else {
        alert('Yay. Location: ' + $scope.location);
    }
  };
}
/* Directives */
angular.module('Gealocation', []).
directive('googlePlaces', function(){
    return {
        restrict:'E',
        replace:true,
        // transclude:true,
        scope: {location:'='},
        template: '<input id="google_places_ac" name="google_places_ac" type="text" class="form-control"/>',
        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()];
                $scope.$apply();
            });
        }
    }
});

geo.controller('SearchForm', SearchForm);

在index.html中,我的输入和自定义指令很少:

<input type="text" class="form-control" ng-model="meeting.topic"></input>
<input type="text" class="form-control" ng-model="meeting.when"></input>
<input type="text" class="form-control" ng-model="meeting.level"></input>
<input type="text" class="form-control" ng-model="meeting.describe"></input>

<google-places location=location></google-places>
<button ng-click="doSearch()" class="btn btn-large btn-primary">Search!</button>

并且从指令i显示值(带有lat和lng的位置)可以通过以下方式实现:

{{location}}

但是我怎么能把这个位置分配给那样的东西:

meeting.location

因为我需要通过以后的对象会议

1 个答案:

答案 0 :(得分:0)

我通过以下方式解决了这个问题:

在控制器中:

$scope.meeting = {
location: ''
};

在视图中:

{{meeting.location = location}}