Angularjs directive controller : wait for DOM to be ready

I'm writing a lineChart directive which loads data from a given url :

<line-chart dataurl="{{ some_url }}"></line-chart>

Then in my lineChart directive, I have a controller which is supposed to load data :

directive('lineChart', function() {
      return {
          restrict: 'EA',
          scope: {
              dataurl: '@'
          },
          controller: function($scope, $http){

            $http.get($scope.dataurl)
                .success(function(data) {
                    $scope.data = data;
                });
          },
          link: function(scope, element, attrs) {
              ...

The problem here is that the controller is called before the DOM is ready, which means that dataurl="" and I get a 404 error. I imagine there is a solution to that using the $timeout service, but I don't need the whole DOM to be ready, only the <line-chart> part. How could I do ?

Thanks.


use the ng-attr-* directive instead to let angular construct the real attribute at the right time :

<line-chart ng-attr-dataurl="some_url"></line-chart>

cf. http://docs.angularjs.org/guide/directive

edit: note that you'll need a $scope.some_url var in your controller

链接地址: http://www.djcxy.com/p/95234.html

上一篇: 在DOM准备就绪后检查元素是否存在

下一篇: Angularjs指令控制器:等待DOM准备就绪