Can not find element in postlink of directive creation in angularjs

懵懂的女人 提交于 2019-12-11 08:27:37

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/15660940/can-not-find-element-in-postlink-of-directive-creation-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!