1

我正在使用ui-router并尝试实例化一个小部件,该小部件将 id 指定的 DOM 元素作为参数。这个 DOM 元素在 a 中<div ng-switch>,我想在保证元素存在时调用小部件构造函数。

<div ng-switch on="state">
  <div ng-switch-when="map">
    <div id="map"></div>
  </div>
</div>

ui-router 生命周期中,我知道我应该挂钩到$viewContentLoaded. 但是,这不起作用 - 此时ng-switch未创建 DOM 元素:

app.config(['$stateProvider', function ($stateProvider) {
  $stateProvider
    .state('/', {url: '/', templateUrl: 'index.html'})
    .state('map', {url: 'map', templateUrl: 'map.html', controller: 'MapCtrl'})
}]);

app.controller('MapCtrl', ['$rootScope', '$scope', '$state', function MapCtrl($rootScope, $scope, $state) {
  $scope.state = $state.current.name;  // expose the state to the template so we can ng-switch. Apparently there's no better way: https://github.com/angular-ui/ui-router/issues/1482

  $scope.$on('$viewContentLoaded', function mapContentLoaded(event, viewConfig) {
    var mapElement = document.getElementById('map');
    console.log('Attempting to create map into', mapElement);
    var map = new google.maps.Map(mapElement);  // <-- but mapElement will be null!
  });
}]);

起作用的是setTimeout()在控制器中使用 50ms 的时间,这很脆弱,但到那时 DOM 元素已创建。或者,我可以设置一个间隔,检查mapDOM 元素是否存在,并在找到时清除间隔。

确定何时渲染其 DOM的正确方法是什么?ng-switch没有记录在案

这是Plunkr

4

1 回答 1

1

我认为你落入了许多有经验的前端开发人员在使用 Angular 时落入的陷阱。在大多数其他 JS 库中,我们在创建 DOM 后对其进行修改,然后为其添加功能。但是,在 Angular 中,功能是在 HTML 中定义的。功能性和交互性是通过使用指令创建的。

在 jQuery中这样的事情很好:

<div id="foobar">
    Click here to do stuff
</div>

<script type="text/javascript">
    $(function () {
        $('#foobar').on('click', function () {
            someService.doStuff();
        });
    });
</script>

在 Angular 中,类似下面的内容更为惯用:

<div id="foobar" ng-controller="Main" ng-click="doStuff()">
    Click here to do stuff
</div>

<script type="text/javascript">
    app.controller('Main', ['$scope', 'somerService', function ($scope, someService) {
        $scope.doStuff = function () {
            someService.doStuff();
        }
    }]);
</script>

至于您的 GoogleMap 指令,这是迄今为止完成它的最简单方法。尽管这是非常基本的,并且可能无法完成您需要的所有操作。

app.directive('googleMap', [function() {
    return {
      link: function(element) {
        new google.maps.Map(element);
      }
    }
  }
]);

你的map.html

<div ng-switch on="state">
  <div ng-switch-when="map">
    <div google-map id="map"></div>
  </div>
</div>

但是,正如您所提到的,每次点击控制器时,这都会重新创建 Google 地图。一种解决方法是保存元素和 Map api,并在后续调用中替换它:

app.directive('googleMap', [function () {
    var googleMapElement,
            googleMapAPI;
    return {
        link: function (element) {
            if (!googleMapElement || !googleMapAPI) {
                googleMapAPI = new google.maps.Map(element);
                googleMapElement = element;
            }
            else {
                element.replaceWith(googleMapElement);
            }

        }
    }
}]);
于 2014-10-27T01:20:20.937 回答