Luis Palomo Luis Palomo - 2 months ago 17
AngularJS Question

Angular Google Maps - Two-way data binding in map-control

I'm having trouble making a map-controller with Angular's two-way data binding expressions:

<script type="text/ng-template" id="control.tpl.html">
<button class="btn btn-sm btn-primary" ng-class="{'btn-warning': danger}" ng-click="controlClick()"><h1>{{controlText}}</h1></button>
</script>

<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" options="options">
<ui-gmap-map-control template="control.tpl.html" position="center" controller="controlCtrl" index="-1"></ui-gmap-map-control>
</ui-gmap-google-map>

<div ng-controller="controlCtrl">
<h1>{{controlText}}</h1>
<label>Two-way Data Binding:</label>
<input ng-model="controlText">
</div>


Here is a Plunker with my problem.

Is there a way to change the binded attribute in the map-control?

Thanks for the help :)

Answer

In order to change the bound attribute in the map-control:

1) introduce a separate controller for the template to share its scope with another controller:

<script type="text/ng-template" id="control.tpl.html">
    <div ng-controller="templateCtrl">
       <button class="btn btn-sm btn-primary" ng-class="{'btn-warning': danger}" ng-click="controlClick()"><h1>{{controlText}}</h1></button>
    </div>   
</script>   

2) Broadcast changes:

$scope.$watch('controlText', function () {
         $rootScope.$broadcast('controlText:changed', $scope.controlText);
});

3) Receive changes in template controller:

.controller('templateCtrl', function ($scope) {
    $scope.$on('controlText:changed', function(event, val) {
       $scope.controlText = val;
    }); 
})     

Plunker

Comments