我正在使用ui-router并尝试实例化一个窗口小部件,该窗口小部件将参数指定为由id指定的DOM元素。这个DOM元素在<div ng-switch>
中,当元素保证存在时,我想调用构造函数。当ng-switch完成渲染时?
<div ng-switch on="state">
<div ng-switch-when="map">
<div id="map"></div>
</div>
</div>
从ui-router lifecycle,我知道我应该挂接到$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!
});
}]);
什么工作是在控制器,它是易碎使用50毫秒的setTimeout()
,但由DOM元素创建的时间。或者,我可以设置一个时间间隔,检查DOM元素是否存在,并在发现时清除时间间隔。
什么是正确ng-switch
何时已经呈现其DOM?这isn't documented。
这是Plunkr。
你混合隐喻/使用DOM方法和角度方法一起使用,不与角度很好地工作领域。使用指令或模板来操作mapElement而不是dom方法。 – dandavis 2014-10-27 00:48:34
你打算如何处理'mapElement'?不管它是什么,@ dandavis都是正确的,你通常只想在指令中进行DOM操作。 – 2014-10-27 00:56:33
@EstebanFelix:我想实例化一个Google Map。刚刚更新了这个问题。我应该怎么做呢?使用ui路由器状态而不是ng-switch? – 2014-10-27 01:04:36