在控制器中,我使用 $http 或 $resource 服务获取一些 JSON 数据。然后我将这些数据写入 $scope 中,AngularJS 更新页面的 HTML 结构。我的问题是我需要知道填充 Angular 的列表(我的意思是 HTML DOM 元素)的新大小(宽度和高度)是多少ng-repeat
指示。因此,我必须在 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());
}
我知道一定有什么简单的方法可以解决这个问题,但我现在找不到它。
实际上在这种情况下,角度方式不是简单的方法,而是唯一正确的方法:)
您必须编写一条指令并将其附加到您想知道其高度的元素。从控制器中,您 $broadcast 一个事件,该指令将捕获该事件,然后您可以进行 DOM 操作。切勿在控制器中。
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);
})
}
};
}]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)