AngularJS 1.2到1.3 clientWidth不再正确

时间:2015-01-16 21:20:31

标签: javascript angularjs

在从1.2更新角度到版本1.3.9时,我遇到了clientWidth之类的障碍。在他们返回正确的DOM值之前,但现在他们返回0.此时元素在DOM中,css将宽度设置为100%,不确定更新角度与此有什么关系。任何见解都会很棒。

提前致谢!

var $m = angular.module('quad.insights.time', ['src/time/time.html','quad.insights.utils']);

$m.directive('timeChart',['$compile','$filter','utils','dateFilter',function($compile,$filter,utils,dateFilter) {
return {
    restrict: 'E',
    replace: true,
    scope: {
        id: '@',
        data: '=',
        metadata: '='
    },
    link: function (scope, element, attrs) {
        window['_timeScope'] = scope;


        scope.render = function() {
            var data = getData();
            if (!data) return;

            function containerWidth() {
             return element[0].querySelector('.qi-time-lines').clientWidth ; // returning 0 with 1.3 update
            }
            function containerHeight() { return element[0].querySelector('.qi-time-lines').clientHeight // returning 0 with 1.3 update }

            var rangeAbs = function(d){ return range(d) * containerHeight() };
            var domainAbs = d3.scale.linear().domain([lowDate,highDate]).range([ 0, containerWidth() ]);
            $compile(element)(scope);
            return;
        }

        scope.$watch('data',scope.render,true);
    },
    templateUrl: 'src/time/time.html'
}
}]);

1 个答案:

答案 0 :(得分:1)

我不知道这是不是最好的方法,但它解决了这个问题:

设置为自定义指令:

angular.module('appControllers').directive('ngChart', function() {
    return function(scope, element, attrs) {
        scope.elementReady(element);
    }
});

然后在控制器上:

$scope.elementReady = function(el){
    console.log(el[0].clientWidth); // <- Right width here
}