【问题标题】:Using custom directive with isolated scope, in a modal在模态中使用具有隔离范围的自定义指令
【发布时间】:2015-01-14 11:12:19
【问题描述】:

我使用自定义指令从 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="address",并用 $watch 填充 ng-model="myaddress",但没有任何反应。

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

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

【问题讨论】:

  • 能否请您创建小号plunkr
  • 我已经用 plunkr 更新了我的帖子
  • 有谁能帮帮我吗?
  • 在 model.html 中,您使用了两个具有不同 ng-model 的输入,例如 address 和 myaddress ...看起来您想将任何内部地址分配给 myaddress 。如果这样,您可以调用一个函数地址模糊并将任何地址分配给 myaddress,例如 --- function onaddresschange(){ $scope.myaddress = address };并从控制器中删除手表

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


【解决方案1】:

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 

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多