javascriptangularjsraphaelgraphaeljustgage

Can not find element in postlink of directive creation in angularjs


I am trying to create a directive for JustGauge in AngularJS. My html view is something like this:

        <div id="guageContainer" class="row" ng-controller="guageCtrl">
            <gauge ng-repeat="ind in indicators" model="ind"></gauge>
        </div>

and my directive is:

angular.module("pgHome", [])
.directive("gauge", function ($compile) {
    return {
        restrict: "E",
        scope: { model: "=model" },
        compile: function (tElement, tAttrs, transclude) {
            tElement.append('<div id="{{model.Name}}"></div>');
            return {
                post: function (scope, iElement, iAttrs, controller) {
                    console.log(scope.model.Name);
                    console.log($("#" + scope.model.Name).length);
                    var g = new JustGage({
                        id: scope.model.Name,
                        value: 348,
                        min: 120,
                        max: 400,
                        title: "test",
                        label: ""
                    });
                }
            };
        }
    };
});

When I load the page containing this directive, JustGauge raises an error saying that it can't find an element with corresponding id. Just to mention that the first console.log works well but the second console.log returns 0. Also I am new to angularjs and I couldn't solve this problem!


Solution

  • Wrap your JustGage() call in a $timeout:

    .directive("gauge", function ($compile, $timeout) {
       ...
       $timeout(function() {
         var g = new JustGage({...});
       });
    

    This gives the browser a chance to render the additional HTML you added in the compile function. Then the plugin can find the newly added div.