在 Controller 中,我使用 $http 或 $resource 服务获取一些 JSON 数据。然后我在 $scope 中写入这些数据,AngularJS 更新页面的 HTML 结构。我的问题是我需要知道用 Angular ng-repeat
指令填充的列表(我的意思是 HTML DOM 元素)的新大小(宽度和高度)是多少。因此,我必须在 Angular 完成更新 DOM 结构后立即运行 javascript 代码。正确的做法是什么?我在过去四个小时内搜索了互联网,但找不到解决问题的方法。
这是我接收 JSON 数据的方式:
var tradesInfo = TradesInfo.get({}, function(data){
console.log(data);
$scope.source.profile = data.profile;
$scope.trades = $scope.source.profile.trades;
$scope.activetrade = $scope.trades[0];
$scope.ready = true;
init(); //I need to call this function after update is complete
});
这就是 init()
函数中发生的事情:
function init(){
alert($('#wrapper').width());
alert($('#wrapper').height());
}
我知道一定有一些容易解决这个问题的方法,但我现在找不到。 提前致谢。
最佳答案
实际上在这种情况下, Angular 方式不是简单的方式,而是唯一正确的方式:)
你必须写一个指令并附加到你想知道高度的元素上。从 Controller $broadcast 一个事件,指令将捕获该事件,然后您可以在那里进行 DOM 操作。永远不要在 Controller 中。
var tradesInfo = TradesInfo.get({}, function(data){
console.log(data);
$scope.source.profile = data.profile;
...
$scope.$broadcast('dataloaded');
});
directive('heightStuff', ['$timeout', function ($timeout) {
return {
link: function ($scope, element, attrs) {
$scope.$on('dataloaded', function () {
$timeout(function () { // You might need this timeout to be sure its run after DOM render.
element.width()
element.height()
}, 0, false);
})
}
};
}]);
关于javascript - 在 AngularJS 完成渲染 HTML 后运行 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16935766/