angularjs - When do we know the actual width of an element in Angular? -
i'm tring create directive center div.
so far, have code:
app.directive("setcenter", function () { return { scope:{ setcenter: '=' }, link: function (scope, element, attrs) { scope.$watch('setcenter', function (newvalue) { if (newvalue == true) { var width = element.width(); element.css('position', 'absolute'); element.css('top', '80px'); element.css('left', '50%'); element.css('z-index', '200'); element.css('margin-left', '-' + width / 2 + 'px'); } }); } } }); the problem width of element. whole point directive div uses directive, don't have width set. want directive figure out width , center div.
the problem encounter when directive invoked, actual width of div not yet known. when use in situation, div 800px, when page finished loading, div 221px.
so, can wait till actual width known of div?
first, have used logic when defined controller directive rather link function. defining in link function instead may cause different behavior, suggest try there first , if can't work switch using controller.
as far can tell, change need make work change $scope scope calls , $element element since dependency injected objects become standard link function parameters.
$scope.getelementdimensions = function () { return { 'h': $element.height(), 'w': $element.width() }; }; $scope.$watch($scope.getelementdimensions, function (newvalue, oldvalue) { //<<perform logic here using newvalue.w , set variables on scope>> }, true); $element.bind('resize', function () { $scope.$apply(); }); the idea usage came me after reading similar type of usage watching $window rather current element, original work can found here.
Comments
Post a Comment