我正在使用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