在模态中使用具有隔离范围的自定义指令

时间:2015-01-14 11:12:20

标签: angularjs angularjs-directive modal-dialog angularjs-scope

我使用自定义指令从Google API获取地点。该指令的工作方式类似于控制器中的魅力。但是当我想在模态中使用它时,它不再起作用了。这是一个范围问题,但我无法弄清楚究竟发生了什么。有什么想法吗?

我的指示:

 'use strict';
angular.module('app').directive('googleplace', function() {
  return {
    require: 'ngModel',
    scope: {
      ngModel: '=',
      details: '=?'
    },
    link: function(scope, element, attrs, model) {
      var options;
      options = {
        types: ['address'],
        componentRestrictions: {}
      };
      scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
      google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
        scope.$apply(function() {
          scope.details = scope.gPlace.getPlace();
          if (scope.details.name) {
            element.val(scope.details.name);
            model.$setViewValue(scope.details.name);
            element.bind('blur', function(value) {
              if (value.currentTarget.value !== '') {
                element.val(scope.details.name);
              }
            });
          }
        });
      });
    }
  };
});

我的模态控制器:

    modalInstance = $modal.open
        templateUrl: "modal.html"
        controller: ($scope, $modalInstance) ->
            $scope.$watch 'placeDetails', ->
              _.forEach $scope.placeDetails.address_components, (val, key) ->
                $scope.myaddress = val.short_name + ' '  if val.types[0] is 'street_number'
                return

最后,我的HTML:

<div class="modal-body">
    <div>
        <input type="text" placeholder="Start typing" ng-model="address" details="placeDetails" googleplace />
    </div>
    <div>
        <input type="text" ng-model="myaddress">
    </div>
</div>

我应该使用调用Google Place API的结果填充ng-model =“地址”,并使用$ watch填充ng-model =“myaddress”,但没有任何反应。

这是我的plunkr http://plnkr.co/edit/iEAooKgfUUfxoBWm8mgw?p=preview

单击“打开模态”会导致错误:无法读取未定义的属性“address_components”

1 个答案:

答案 0 :(得分:0)

working demo

According to how to create modal in angularjs

Extra things that i added : 

1 : New Controller for modal

2 : Blur function that fires on property change Instead of $watch